C++ Program For Removing Duplicates From An Unsorted Linked List
Last Updated :
24 Mar, 2023
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.
C++
// C++ Program to remove duplicates in an
// unsorted linked list
#include <bits/stdc++.h>
using namespace std;
// A linked list node
struct Node
{
int data;
struct Node* next;
};
// Utility function to create a
// new Node
struct Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
/* Function to remove duplicates from a
unsorted linked list */
void removeDuplicates(struct Node* start)
{
struct Node *ptr1, *ptr2, *dup;
ptr1 = start;
// Pick elements one by one
while (ptr1 != NULL &&
ptr1->next != NULL)
{
ptr2 = ptr1;
/* Compare the picked element with rest
of the elements */
while (ptr2->next != NULL)
{
/* If duplicate then delete it */
if (ptr1->data == ptr2->next->data)
{
// Sequence of steps is important here
dup = ptr2->next;
ptr2->next = ptr2->next->next;
delete (dup);
}
else
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
}
// Function to print nodes in a given
// linked list
void printList(struct Node* node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
// Driver code
int main()
{
// The constructed linked list is:
// 10->12->11->11->12->11->10
struct Node* start = newNode(10);
start->next = newNode(12);
start->next->next = newNode(11);
start->next->next->next = newNode(11);
start->next->next->next->next = newNode(12);
start->next->next->next->next->next = newNode(11);
start->next->next->next->next->next->next = newNode(10);
printf("Linked list before removing duplicates ");
printList(start);
removeDuplicates(start);
printf("Linked list after removing duplicates ");
printList(start);
return 0;
}
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.
C++
// C++ Program to remove duplicates in an
// unsorted linked list
#include<bits/stdc++.h>
using namespace std;
// A linked list node
struct Node
{
int data;
struct Node *next;
};
// Utility function to create a
// new Node
struct Node *newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
/* Function to remove duplicates from a
unsorted linked list */
void removeDuplicates(struct Node *start)
{
// Hash to store seen values
unordered_set<int> seen;
// Pick elements one by one
struct Node *curr = start;
struct Node *prev = NULL;
while (curr != NULL)
{
// If current value is seen before
if (seen.find(curr->data) != seen.end())
{
prev->next = curr->next;
delete (curr);
}
else
{
seen.insert(curr->data);
prev = curr;
}
curr = prev->next;
}
}
// Function to print nodes in a given
// linked list
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
// Driver code
int main()
{
/* The constructed linked list is:
10->12->11->11->12->11->10*/
struct Node *start = newNode(10);
start->next = newNode(12);
start->next->next = newNode(11);
start->next->next->next = newNode(11);
start->next->next->next->next = newNode(12);
start->next->next->next->next->next = newNode(11);
start->next->next->next->next->next->next = newNode(10);
printf("Linked list before removing duplicates : ");
printList(start);
removeDuplicates(start);
printf("Linked list after removing duplicates : ");
printList(start);
return 0;
}
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!
Similar Reads
C++ Program For Removing Duplicates From A Sorted Linked List Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
9 min read
C++ Program For Removing All Occurrences Of Duplicates From A Sorted Linked List Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list. Examples: Input: 23->28->28->35->49->49->53->53 Output: 23->35 Input: 11->11->11->11->75->75 Output: empty Li
4 min read
C++ Program To Remove Duplicates From Sorted Array Given a sorted array, the task is to remove the duplicate elements from the array.Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: arr[] = {2} new size = 1 Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5} Output: arr[] = {1, 2, 3, 4, 5} new size = 5 Recommended PracticeRemove duplicate elements from sorte
3 min read
C++ Program For Writing A Function To Delete A Linked List Algorithm For C++:Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted. Implementation: C++ // C++ program to delete a linked list #include <bits/stdc++.h> using namespace std
2 min read
C++ Program For Insertion Sort In A Singly Linked List We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
5 min read
C++ Program For Merge Sort For Doubly Linked List Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
3 min read
C++ Program for Last duplicate element in a sorted array We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
2 min read
C++ Program For Removing Every K-th Node Of The Linked List Given a singly linked list, Your task is to remove every K-th node of the linked list. Assume that K is always less than or equal to length of Linked List.Examples : Input: 1->2->3->4->5->6->7->8 k = 3 Output: 1->2->4->5->7->8 As 3 is the k-th node after its deletion list would be 1->2->4->5->6->7->
3 min read
C++ Program For Finding Intersection Of Two Sorted Linked Lists Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory â the original lists should not be changed. Example: Input: First linked list: 1->2->3->4->6 Second linked list be 2-
6 min read
C++ Program For Comparing Two Strings Represented As Linked Lists Given two strings, represented as linked lists (every character is a node in a linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are the same, 1 if the first linked list is lexicographically greater, and -1 if the second string is lexicograph
2 min read