top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to remove duplicates from an unordered linked list?

0 votes
346 views

Please help me to achieve this, c/c++ code would be very helpful?

posted Jul 12, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Algorithm
1. Take two loops say loop outer and loop inner.
2. Run the outer loop from start to end and picks one element on each iteration.
3. Inner loop loop compares the picked element with rest of the elements.

Assume you Linklist node is looking like this

struct node
{
 int data;
 struct node *next;
};

Sample Code

void remove_duplicates(struct node *start)
{
  struct node *ptr1, *ptr2, *dup;
  ptr1 = start;

  /* Outer Loop */
  while(ptr1 != NULL && ptr1->next != NULL)
  {
     ptr2 = ptr1;

     /* Inner Loop - Compare the picked element with rest of the elements */
     while(ptr2->next != NULL)
     {
       if(ptr1->data == ptr2->next->data)
       {
          /* Duplicate - Delete the node */
          dup = ptr2->next;
          ptr2->next = ptr2->next->next;
          free(dup);
       }
       else 
       {
          ptr2 = ptr2->next;
       }
     }
     ptr1 = ptr1->next;
  }
}
answer Jul 14, 2014 by Salil Agrawal
...