poorvankBhatia poorvankBhatia - 1 year ago 74
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;
return start;

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download