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,Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return 2->3.

public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode tail = dummy;
        ListNode p1 = head;
        ListNode p2 = head;
        while(p1!=null&&p1.next!=null)
        {
            while(p1.next != null&&p1.val == p1.next.val)
            {
                p1 = p1.next;
            }
            if(p1 == p2)
            {
                tail.next = p2;
                tail = tail.next;
            }
            p2 = p1.next;
            p1 = p2;
        }
        tail.next = p1;  // 加入最后一个元素
        return dummy.next;
    }
}

你可能感兴趣的:(82. Remove Duplicates from Sorted List II)