题解 | #删除有序链表中重复的元素-II#

删除有序链表中重复的元素-II

http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* deleteDuplicates(ListNode* head) {
        // write code here
        if(!head) return nullptr;
        ListNode *pre, *cur;
        int rec = INT_MIN;                           //for recording the duplicate num
        ListNode* newHead = new ListNode(INT_MIN);   //the node for convenient traversal
        newHead->next = head;
        pre = newHead;
        cur = head;
        while(cur && cur->next)
        {
             ListNode* next = cur->next;
             if(cur->val == next->val) 
             {
                 rec = cur->val;
                 while(cur && cur->val == rec)
                 {
                      delete(cur);
                      cur = next;
                      if(next) next = next->next;
                 }
                 pre->next = cur;
            }
            else{
                    pre = cur;
                    cur = cur->next;
            }
        }
        cur = newHead->next;
        delete(newHead);  // avoid memory leak
        return cur;
    }
};
全部评论

相关推荐

杨柳哥:这不是普通人,那这个钱的是天才
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务