[Linked List]Remove Duplicates from Sorted List II

Total Accepted: 59433 Total Submissions: 230628 Difficulty: Medium

 

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* help_node = new ListNode(0);
        help_node->next     = head;
        
        ListNode* cur_pre  = help_node;
        ListNode* cur      = head;
        
        while(cur!=NULL){
            ListNode* p = cur->next;
            while(p!=NULL && p->val==cur->val){
                p = p->next;
            }
            
            if(p != cur->next){
                while(cur != p) {
                    ListNode* tmp = cur;
                    cur           = cur->next;
                    delete (tmp);
                }
            
                cur_pre->next = p;
                cur           = p;
            }else{
                cur_pre = cur;
                cur     = cur->next;
            }
        }
        
        head = help_node->next;
        delete (help_node);
        return head;
    }
};

 

posted @ 2015-12-12 18:35  zengzy  阅读(160)  评论(0编辑  收藏  举报
levels of contents