poorvankBhatia poorvankBhatia - 22 days ago 7
C Question

Remove duplicate elements from a sorted linked list

I am attempting a C program to remove duplicates from a Sorted linked list and i am using a simple concept of traversing the list from the start node. While traversing, compare each node with its next node. If data of next node is same as current node then i delete the next node.

My Code is:

struct node *remove_dup(struct node *start)
{
struct node *p,*tmp;
p=start;
while(p!=NULL)
{
if(p->info==p->link->info)
{
tmp=p->link;
p->link=p->link->link;
free(tmp);
}
p=p->link;
}
return start;
}


It is not giving me the correct answer! What is wrong with my execution? Is my concept wrong?

Answer

Since your code examines the next element, you need to stop when you are at the element one before last, like this:

while (p != NULL && p->link != NULL) {
    ...
}

The only reason to have the first part of the condition is to trap empty lists.

In addition, you should not advance the pointer when you remove an element. Otherwise, you would not process runs of more than two elements correctly.