Open In App

C++ Program For Removing Duplicates From An Unsorted Linked List

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted. 
For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43.

METHOD 1 (Using two loops): 
This is the simple way where two loops are used. Outer loop is used to pick the elements one by one and the inner loop compares the picked element with the rest of the elements. 
Thanks to Gaurav Saxena for his help in writing this code.

Output: 

Linked list before removing duplicates:
10 12 11 11 12 11 10 
Linked list after removing duplicates:
10 12 11

Time Complexity: O(n^2)

Auxiliary Space: O(1)

METHOD 2 (Use Sorting): 
In general, Merge Sort is the best-suited sorting algorithm for sorting linked lists efficiently. 
1) Sort the elements using Merge Sort. We will soon be writing a post about sorting a linked list. O(nLogn) 
2) Remove duplicates in linear time using the algorithm for removing duplicates in sorted Linked List. O(n) 
Please note that this method doesn't preserve the original order of elements.
Time Complexity: O(nLogn)

METHOD 3 (Use Hashing): 
We traverse the link list from head to end. For every newly encountered element, we check whether it is in the hash table: if yes, we remove it; otherwise we put it in the hash table.

Output: 

Linked list before removing duplicates:
10 12 11 11 12 11 10 
Linked list after removing duplicates:
10 12 11

Thanks to bearwang for suggesting this method.
Time Complexity: O(n) on average (assuming that hash table access time is O(1) on average).

Please refer complete article on Remove duplicates from an unsorted linked list for more details!


Explore