cztchoice
1/19/2014 - 1:15 AM

Remove Duplicates from Sorted List II http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

/**
 * 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) {
        if(head == NULL || head->next == NULL){
            return head;
        }
        /*while(head->next != NULL && head->val == head->next->val){
            head = head->next;
        }*/
        ListNode *first = new ListNode(0);
        first->next = head;
        ListNode *it = first;
        //ListNode *pre = first;
        
        while(it->next && it->next->next){
             if(it->next->val == it->next->next->val){
                 while(it->next && it->next->next && it->next->val == it->next->next->val){
                    ListNode *temp = it->next;
                    it->next = temp->next;
                    delete temp;
                 }
                 ListNode *temp = it->next;
                 it->next = temp->next;
                 delete temp;
             }
             else{
                 it = it->next;
                 //pre = pre->next;
             }
        }
        
        ListNode *re = first->next;
        delete first;
        return re;
    }
};