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.

C++:
01 ListNode *deleteDuplicates(ListNode *head)
02  {
03       if(head==NULL)
04           return NULL;
05       ListNode* tmp=head;
06       while(tmp){
07           int data=tmp->val;
08           ListNode* p=tmp->next;
09           if(p==NULL)
10             return head;
11           while(p->val==data){
12               p=p->next;
13               if(p==NULL){
14                   tmp->next=p;
15                   return head;
16               }
17           }
18           tmp->next=p;
19           tmp=p;
20       }
21       return head;
22 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s