Remove duplicates from an unsorted linked list.

Write code to remove duplicates from an unsorted linked list.

FOLLOW UP

How would you solve this problem if a temporary buffer is not allowed?

C++:
01 void rmDuplicate(Node* head)
02 {
03     set <int> s;
04     Node* prv=head;
05     while(head){
06         int data=head->value;
07         if(s.find(data)==s.end()){
08             s.insert(data);
09             prv=head;
10             head=head->next;
11         }
12         else{
13             prv->next=head->next;
14             delete head;
15             head=prv->next;
16         }
17     }
18 }

When temporary buffer is not allowed, we can check each element to see if there exists a duplicate before it. Then the time complexity becomes O(n^2).

C++:
01 void rmDuplicate(Node* head)
02 {
03     Node* prv=head;
04     Node* tmp=head;
05     Node* check=head;
06     bool dup=false;
07     while(tmp){
08         for(check=head;check!=tmp;check=check->next){
09             if(check->value==tmp->value){
10                 dup=true;
11                 break;
12             }
13         }
14         if(!dup){
15             prv=tmp;
16             tmp=tmp->next;
17         }
18         else{
19             prv->next=tmp->next;
20             delete tmp;
21             tmp=prv->next;
22             dup=false;
23         }
24     }
25 }

Alternatively, if we do not need to keep the order, we can first sort the linked list, then remove the duplicates.

 

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