Friday, April 11, 2014

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.
Solution:
Simple implementation
Code:
    ListNode *deleteDuplicates(ListNode *head) {
       ListNode* cur;
       int val;

       if(!head || !head->next) return head;

       cur = head;
       val = head->val;

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

No comments:

Post a Comment