Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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
posted on 2014-08-03 07:04  Tonix  阅读(157)  评论(0编辑  收藏  举报