题解 | #删除有序链表中重复的元素-II#

删除有序链表中重复的元素-II

http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        if(head==null) return null;
        ListNode res=new ListNode(-1);
        ListNode cur=res; 
        res.next=head; 
          while(cur.next != null && cur.next.next != null){//两个以上结点
            //遇到相邻两个节点值相同
            if(cur.next.val == cur.next.next.val){
                int temp = cur.next.val;//保存相同的结点值
                //将所有相同的都跳过
                while (cur.next != null && cur.next.val == temp)//只要等于相同的节点值,就跳过
                    cur.next = cur.next.next;
            }
            else
                cur = cur.next;
        }
        //返回时去掉表头
        return res.next;
        
    }
}
全部评论

相关推荐

04-09 11:42
门头沟学院 Java
程序员小假:哥 只有🍋飞才知道有多不容易
投递字节跳动等公司9个岗位 > 双非本科求职如何逆袭 字节求职进展汇总
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务