Write a C program to remove duplicates from a sorted linked list



Answered by Manish Kumar 

Linked list are sorted, so we can start from the begining of the list and compare adjacent nodes. when we find that adjacent nodes are same just remove the second one. Also we have to check the node after the next node as there may be three duplicate adjacent nodes.

//Program to duplicates from a sorted list

 void RemoveDuplicates(struct node* head)
 {
  struct node* current = head;
  if (current == NULL) return;  // do nothing if the list is empty

  // Compare current node with next node

  while(current->next!=NULL)
  {
     if (current->data == current->next->data)     
        { 
            struct node* nextNext = current->next->next;
            free(current->next);
            current->next = nextNext;
        } 
    else 
        { 
            current = current->next; // move to next if no deletion 
        }
  } 
 }