How to Remove Duplicate Entries from Linked List?

Here we’ll see how to write C program to remove duplicate entries from linked list. Linked list contains duplicate entries when nodes with same value appear multiple times in the list.

Remove Duplicate Entries from Linked List

In the above Linked list entries, 43, 24 and 5 appeared more than once. We’ll write a C program to remove these duplicate elements such that they appear only once in the resulted linked list along with other non-duplicate elements. Another important thing, the order of the elements will remain intact in the resulted linked list. The result will look like this.Linked list after removing duplicate entry

C Program to Remove Duplicate Entries from Linked List

Output of the Program

If you run the program the output would look like

Explanation of the Program

The program takes input from user to construct the linked list. The user needs to enter some duplicate entries to see the affect. The remove_duplicate() function is used to remove duplicate entries from the linked list passed as argument.

Logic is simple. The outer loop takes a node in every iteration starting from the first node and compares its value will rest of the right nodes in the list. If the value of any other node matches with outer loop node, the inner loop deletes that node from the linked list. The delete_node() function is used to delete the node. When the outer loop reaches end of the linked list, the linked list becomes duplicate entry free. The time complexity of the remove_duplicate() function is O(n2).

Leave a Reply

Your email address will not be published. Required fields are marked *