Friday, April 11, 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.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
Code:
ListNode *deleteDuplicatesII(ListNode *head) {
    if (head==NULL || head->next==NULL)
        return head;

    ListNode *first = new ListNode(10);

    first->next = head;
    head = first;

    ListNode * pre = head;
    ListNode * cur = head;

    while(cur && cur->next)
    {
        if (cur->val == cur->next->val)
        {
            while (cur->next && cur->next->val == cur->val)
            {
                ListNode * tmp  = cur->next;
                delete cur;
                cur = tmp;
            }

            pre->next = cur->next;
            delete cur;
            cur = pre->next;
        }
        else
        {
            pre = cur;
            cur = cur->next;
        }
    }

    ListNode *tmp = head->next;
    delete head;
    head = tmp;

    return head;
}

No comments:

Post a Comment