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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容