[leedcode 82] Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    //本题自我感觉很难,主要突破点:
    //1:注意要声明一个节点p,该节点的前面代表已经满足要求的
    //s节点代表重复值得第一位,通过遍历t比较t指向的值是否等于s,当相等时,这里很重要,通过比较s.next==t可知,是否有重复变量,
    //如果有重复变量,直接使得p指向t,如果没有重复遍历,需要保存s的节点
    //最后需要考虑s是否已经遍历到最后一位,如果s没有遍历到最后一位,而t遍历到了最后,说明s到t中间有重复值,即s要舍弃,所以p.next=null
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode newHead=new ListNode(-1);
        newHead.next=head;
        ListNode p=newHead;
        ListNode s=head;
        ListNode t=head.next;
        while(t!=null){
            if(t.val==s.val){
                t=t.next;
            }else{
                if(s.next==t){
                    //p.next=s;
                    p=s;
                    s=t;
                    t=t.next;
                }else{
                    p.next=t;
                    s=t;
                    t=t.next;
                    
                }
            }
           
        }
        if(s.next!=null){
            p.next=null;
        }
        return newHead.next;
    }
}
原文地址:https://www.cnblogs.com/qiaomu/p/4648756.html