LeetCode-082. Remove Duplicates from Sorted List II

1. 題目

Remove Duplicates from Sorted List II

對有序鏈表去重,刪掉所有的重複元素

2. 分析

若鏈表長度小於2,直接結束
否則,遍歷鏈表,當相鄰元素相等時,刪除所有重複元素

3. 代碼

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;

        ListNode *dummy = new ListNode(INT_MIN);
        dummy->next = head;

        ListNode *pre = dummy;
        while(pre != NULL)
        {
            ListNode *cur = pre->next;
            while(cur && cur->next && cur->val == cur->next->val)
                cur = cur->next;
            if(pre->next != cur)
                pre->next = cur->next;
            // 注意不要遺漏else
            // 否則會出錯,如 [1,2,3,3,4,4,5] 會得到 [1,2,4,4,5]
            else
                pre = pre->next;
        }

        return dummy->next;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章