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;
    }
};

完整源代码放于github

猜你喜欢

转载自blog.csdn.net/tao_ba/article/details/80656841