Leetcode 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.

題意:83題的followup,這次重復(fù)的元素一個都不保留了。

思路:問題的關(guān)鍵是如果判斷一個元素是不是非重復(fù)元素,判斷的條件就是它不和前面的元素相等也不和后面的元素相等。由于是鏈表,我們需要用一個變量記錄前面的listnode,才能判斷。還有一點需要注意的就是頭尾節(jié)點是沒有pre和next的,注意pre和next是否是null的判斷。
所以本題需要三個指針,dummy指向已連接起來的符合條件的節(jié)點,cur指向當(dāng)前遍歷到的節(jié)點,pre指向cur前面一個節(jié)點,每遍歷到一個節(jié)點,如果它和前后都不相等,就把dummy.next指向它,然后把dummy更新為dummy.next。

public ListNode deleteDuplicates(ListNode head) {
    ListNode res = new ListNode(0);
    if (head == null || head.next == null) {
        return head;
    }

    ListNode dummy = res;
    ListNode pre = null;
    ListNode cur = head;
    while (cur != null) {
        if ((pre != null && cur.next != null && cur.val != pre.val && cur.val != cur.next.val)
                || (pre == null && cur.next != null && cur.val != cur.next.val)
                || (cur.next == null && cur.val != pre.val)) {
            dummy.next = cur;
            dummy = dummy.next;
        }
        pre = cur;
        cur = cur.next;
    }
    dummy.next = null;

    return res.next;
}

bug:最后又疏忽了要把dummy.next指向null,不然1,2,3,3這種case就會fail。

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

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