首页 > 代码库 > LeetCode "Remove Duplicates from Sorted List II"

LeetCode "Remove Duplicates from Sorted List II"

Corner cases!

class Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        if (!head) return head;        if (!head->next) return head;                ListNode dum(-1); dum.next = head;        ListNode *pPre = &dum;        ListNode *p1 = head;        int cnt = 0;        int last = std::numeric_limits<int>::max();        while (p1)        {            //    A new one?            if (p1->val != last)            {                if (cnt > 1)                {                    pPre->next = p1;                    last = p1->val;                }                else                {                    last = p1->val;                    while (pPre->next != p1) pPre = pPre->next;                                    }                cnt = 1;            }            else            {                cnt++;            }            p1 = p1->next;        }        if (cnt > 1)        {            if (pPre == &dum) return NULL;            else            {                pPre->next = NULL;            }        };        return dum.next;    }};
View Code