Write a C program to remove duplicates from a sorted linked list
![]() Don't want to miss a single bit? Subscribe By Email for Daily Jobs |
As the linked list is sorted, we can start from the beginning of the list and compare adjacent nodes. When adjacent nodes are the same, remove the second one. There’s a tricky case where the node after the next node needs to be noted before the deletion.
// Remove 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; // only advance if no deletion
}
}
}
Related Articles
- Write a C program to insert nodes into a linked list in a sorted fashion
- How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list.
- How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list.
- How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list.How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list.
- Write a C program to find the mininum value in a binary search tree.


