Online Judge Solutions

Tuesday, December 30, 2014

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.
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:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode * deleteDuplicates(ListNode *head) {
        ListNode dummy(0);
        
        dummy.next = head;
        ListNode *p = &dummy;
        
        while(p->next && p->next->next) {
            if (p->next->val == p->next->next->val) {
                int val = p->next->val;
                while(p->next && p->next->val == val) {
                    ListNode *next = p->next->next;
                    delete p->next;
                    p->next = next;
                }
            }
            else
               p = p->next;
        }
        return dummy.next;
    }
};

No comments:

Post a Comment