Choose Skin

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

Manish Kumar
February 16, 2018

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

     if (current->data == current->next->data)     
            struct node* nextNext = current->next->next;
            current->next = nextNext;
            current = current->next; // move to next if no deletion 

  Refine your Search