Sunday, April 26, 2015

[LeetCode] Remove Duplicates from Sorted List II

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.
Analysis:

Firstly we need to maintain a pointer for the previous node of the visiting one. If the visiting node is equal to the next one, find the node which is equal to the visiting one but is not equal to its next one. Remove the duplicate nodes.
/**
 * 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) {
        ListNode dummy(0);
        ListNode *prev = &dummy;
        prev->next = head;
        while(head)
        {
            ListNode *next = NULL;
            while(head->next && 
                  head->val == head->next->val)
            {
                next = head->next;
                delete head;
                head = next;
            }
            if(next)
            {   
                prev->next= next->next;
                delete head;
                head = next->next;
            }
            else 
            {
                prev = head;
                head = head->next;
            }
        }
        return dummy.next;
    }
};