C++ Program For Removing Duplicates From A Sorted Linked List
Last Updated :
15 Jun, 2022
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->60.
Algorithm:
Traverse the list from the head (or start) node. While traversing, compare each node with its next node. If the data of the next node is the same as the current node then delete the next node. Before we delete a node, we need to store the next pointer of the node
Implementation:
Functions other than removeDuplicates() are just to create a linked list and test removeDuplicates().
C++
// C++ Program to remove duplicates
// from a sorted linked list
#include <bits/stdc++.h>
using namespace std;
// Link list node
class Node
{
public:
int data;
Node* next;
};
// The function removes duplicates
// from a sorted list
void removeDuplicates(Node* head)
{
// Pointer to traverse the linked list
Node* current = head;
// Pointer to store the next pointer
// of a node to be deleted
Node* next_next;
// Do nothing if the list is empty
if (current == NULL)
return;
// Traverse the list till last node
while (current->next != NULL)
{
// Compare current node with next node
if (current->data == current->next->data)
{
// The sequence of steps is important
next_next = current->next->next;
free(current->next);
current->next = next_next;
}
// This is tricky: only advance if no deletion
else
{
current = current->next;
}
}
}
// UTILITY FUNCTIONS
// Function to insert a node at the
// beginning of the linked list
void push(Node** head_ref, int new_data)
{
// Allocate node
Node* new_node = new Node();
// Put in the data
new_node->data = new_data;
// Link the old list off the
// new node
new_node->next = (*head_ref);
// Move the head to point to the
// new node
(*head_ref) = new_node;
}
// Function to print nodes in a
// given linked list
void printList(Node *node)
{
while (node != NULL)
{
cout << " " << node->data;
node = node->next;
}
}
// Driver code
int main()
{
// Start with the empty list
Node* head = NULL;
/* Let us create a sorted linked list
to test the functions. Created
linked list will be
11->11->11->13->13->20 */
push(&head, 20);
push(&head, 13);
push(&head, 13);
push(&head, 11);
push(&head, 11);
push(&head, 11);
cout << "Linked list before duplicate removal ";
printList(head);
// Remove duplicates from linked list
removeDuplicates(head);
cout << "Linked list after duplicate removal ";
printList(head);
return 0;
}
// This code is contributed by rathbhupendra
Output:
Linked list before duplicate removal 11 11 11 13 13 20
Linked list after duplicate removal 11 13 20
Time Complexity: O(n) where n is the number of nodes in the given linked list.
Auxiliary Space: O(1)
Recursive Approach :
C++
// C++ Program to remove duplicates
// from a sorted linked list
#include <bits/stdc++.h>
using namespace std;
// Link list node
class Node
{
public:
int data;
Node* next;
};
// The function removes duplicates
// from a sorted list
void removeDuplicates(Node* head)
{
// Pointer to store the pointer
// of a node to be deleted*/
Node* to_free;
// Do nothing if the list is empty
if (head == NULL)
return;
// Traverse the list till last node
if (head->next != NULL)
{
// Compare head node with next node
if (head->data == head->next->data)
{
/* The sequence of steps is important.
to_free pointer stores the next of
head pointer which is to be deleted.*/
to_free = head->next;
head->next = head->next->next;
free(to_free);
removeDuplicates(head);
}
/* This is tricky: only advance if
no deletion */
else
{
removeDuplicates(head->next);
}
}
}
// UTILITY FUNCTIONS
// Function to insert a node at the
// beginning of the linked list
void push(Node** head_ref,
int new_data)
{
// Allocate node
Node* new_node = new Node();
// Put in the data
new_node->data = new_data;
// Link the old list off the
// new node
new_node->next = (*head_ref);
// Move the head to point to
// the new node
(*head_ref) = new_node;
}
/* Function to print nodes
in a given linked list */
void printList(Node *node)
{
while (node != NULL)
{
cout << " " << node->data;
node = node->next;
}
}
// Driver code
int main()
{
// Start with the empty list
Node* head = NULL;
/* Let us create a sorted linked
list to test the functions
Created linked list will be
11->11->11->13->13->20 */
push(&head, 20);
push(&head, 13);
push(&head, 13);
push(&head, 11);
push(&head, 11);
push(&head, 11);
cout <<
"Linked list before duplicate removal ";
printList(head);
// Remove duplicates from linked list
removeDuplicates(head);
cout <<
"Linked list after duplicate removal ";
printList(head);
return 0;
}
// This code is contributed by Ashita Gupta
Output:
Linked list before duplicate removal 11 11 11 13 13 20
Linked list after duplicate removal 11 13 20
Time Complexity: O(n), where n is the number of nodes in the given linked list.
Auxiliary Space: O(n), due to recursive stack where n is the number of nodes in the given linked list.
Another Approach: Create a pointer that will point towards the first occurrence of every element and another pointer temp which will iterate to every element and when the value of the previous pointer is not equal to the temp pointer, we will set the pointer of the previous pointer to the first occurrence of another node.
Below is the implementation of the above approach:
C++
// C++ program to remove duplicates
// from a sorted linked list
#include <bits/stdc++.h>
using namespace std;
// Linked list Node
struct Node
{
int data;
Node *next;
Node(int d)
{
data = d;
next = NULL;
}
};
// Function to remove duplicates
// from the given linked list
Node *removeDuplicates(Node *head)
{
// Two references to head temp will
// iterate to the whole Linked List
// prev will point towards the first
// occurrence of every element
Node *temp = head,*prev=head;
// Traverse list till the last node
while (temp != NULL)
{
// Compare values of both pointers
if(temp->data != prev->data)
{
/* if the value of prev is not equal
to the value of temp that means
there are no more occurrences of
the prev data-> So we can set the
next of prev to the temp node->*/
prev->next = temp;
prev = temp;
}
// Set the temp to the next node
temp = temp->next;
}
/* This is the edge case if there are more than
one occurrences of the last element */
if(prev != temp)
{
prev->next = NULL;
}
return head;
}
Node *push(Node *head, int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node *new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node->next = head;
/* 4. Move the head to point to new Node */
head = new_node;
return head;
}
// Function to print linked list
void printList(Node *head)
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// Driver code
int main()
{
Node *llist = NULL;
llist = push(llist,20);
llist = push(llist,13);
llist = push(llist,13);
llist = push(llist,11);
llist = push(llist,11);
llist = push(llist,11);
cout <<
("List before removal of duplicates");
printList(llist);
cout <<
("List after removal of elements");
llist = removeDuplicates(llist);
printList(llist);
}
// This code is contributed by mohit kumar 29.
Output:
List before removal of duplicates
11 11 11 13 13 20
List after removal of elements
11 13 20
Time Complexity: O(n) where n is the number of nodes in the given linked list.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Another Approach: Using Maps
The idea is to push all the values in a map and printing its keys.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct Node
{
int data;
Node* next;
Node()
{
data = 0;
next = NULL;
}
};
/* Function to insert a node at
the beginning of the linked
list */
void push(Node** head_ref,
int new_data)
{
// Allocate node
Node* new_node = new Node();
// Put in the data
new_node->data = new_data;
// Link the old list off
// the new node
new_node->next = (*head_ref);
// Move the head to point
// to the new node
(*head_ref) = new_node;
}
/* Function to print nodes
in a given linked list */
void printList(Node* node)
{
while (node != NULL)
{
cout << node->data << " ";
node = node->next;
}
}
// Function to remove duplicates
void removeDuplicates(Node* head)
{
unordered_map<int, bool> track;
Node* temp = head;
while (temp)
{
if (track.find(temp->data) == track.end())
{
cout << temp->data << " ";
}
track[temp->data] = true;
temp = temp->next;
}
}
// Driver Code
int main()
{
Node* head = NULL;
/* Created linked list will be
11->11->11->13->13->20 */
push(&head, 20);
push(&head, 13);
push(&head, 13);
push(&head, 11);
push(&head, 11);
push(&head, 11);
cout <<
"Linked list before duplicate removal ";
printList(head);
cout <<
"Linked list after duplicate removal ";
removeDuplicates(head);
return 0;
}
// This code is contributed by yashbeersingh42
Output:
Linked list before duplicate removal 11 11 11 13 13 20
Linked list after duplicate removal 11 13 20
Time Complexity: O(n) where n is the number of nodes.
Auxiliary Space: O(n) where n is the number of nodes.
Please refer complete article on Remove duplicates from a sorted linked list for more details!
Similar Reads
C++ Program For Removing Duplicates From An Unsorted Linked List
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. Recommended:
4 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 Reversing A Doubly Linked List
Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes
5 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 Removing Middle Points From a Linked List Of Line Segments
Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line.Examples: Input: (0,10)->(1,10)->(5,10)->(7,10) | (7,5)->(20,5)->(40,5) Output: Linked
4 min read