Friday, October 10, 2014

[leetcode] Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.


ListNode *deleteDuplicates(ListNode *head) {
        ListNode* curr = head;
        while(curr != NULL && curr->next != NULL)
        {
   //if curr node value is equal to the next node value, remove the next node
            if (curr->val == curr->next->val)
            {
                ListNode* tmp = curr->next;
                curr->next = curr->next->next;
                delete tmp;
            }
            else
            {
    //otherwise, move to next node
                curr = curr->next;
            }
        }
        return head;
    }

No comments:

Post a Comment