leetcode82. Remove Duplicates from Sorted List II

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode82. Remove Duplicates from Sorted List II相关的知识,希望对你有一定的参考价值。

利用虚拟节点进行删除结点,pre始终指向不重复的钱一个元素,一开始指向虚拟结点。如果遇到重复结点就全部删除再与pre相连接.

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* dummyNode;
        dummyNode = new ListNode(0);
        dummyNode->next = head;
        ListNode* pre;
        pre = dummyNode;
        ListNode* cur;
        cur = head;
        if (head == NULL)
            return NULL;
        while (cur->next!=NULL)//pre指向没重复的前一个元素,cur指向当前元素
        {
            if(cur->next->val == cur->val)
            {
                if(cur->val == cur->next->val)
                {
                    int val = cur->val;
                    while (cur!=NULL&&cur->val == val)
                    {
                        ListNode* delNode;
                        delNode = cur;
                        cur = cur->next;
                        delete delNode;
                    }
                    pre->next = cur;
                    if (cur == NULL)
                        break;
                }
            }
            else
            {
                pre = cur;
                cur = cur->next;
            }
        }
        return dummyNode->next;
    }
};

 

以上是关于leetcode82. Remove Duplicates from Sorted List II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 82 Remove Duplicates from Sorted List II

LeetCode82 Remove Duplicates from Sorted List II

[LeetCode]82. Remove Duplicates from Sorted List II

[LeetCode] 82. Remove Duplicates from Sorted List II

leetcode:82. Remove Duplicates from Sorted List II(Java)解答

一天一道LeetCode#82. Remove Duplicates from Sorted List II