Saturday, September 20, 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.

 /**  
  * Definition for singly-linked list.  
  * struct ListNode {  
  *   int val;  
  *   ListNode *next;  
  *   ListNode(int x) : val(x), next(NULL) {}  
  * };  
  */  

   ListNode *deleteDuplicates(ListNode *head) {  
     if(!head || !head->next)return head;  
     ListNode *prev = head, *cur = head->next;  
     while(cur)  
     {  
       while(cur && cur->val == prev->val)  
       {  
         prev->next = cur->next;  
         ListNode *tmp = cur;  
         cur = cur->next;  
         delete tmp;  
       }  
       if (cur)  
       {  
         prev = cur;  
         cur = cur->next;  
       }  
     }  
     prev->next = NULL;  
     return head;  
   }  

No comments:

Post a Comment