Thursday, 2 August 2012

C program to remove duplicates from a linked list

First sort the linked list.

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
}
}
}

1 comment:

  1. I am really enjoying the theme/design of your website.
    Do you ever run into any web browser compatibility issues?
    A few of my blog audience have complained about my site not operating correctly
    in Explorer but looks great in Firefox. Do you have any tips to help fix this problem?



    Also visit my site :: Delete Duplicate Files

    ReplyDelete