Given a linked list sorted in non-decreasing order. Return the list by deleting the duplicate nodes from the list. The returned list should also be in non-decreasing order.
Example:
Input : Linked List = 11->11->11->21->43->43->60 Output : 11->21->43->60 Explanation:
[Naive Approach] Remove duplicates using HashSet – O(n) Time and O(n) Space:
The idea is to traverse the linked list and check if the value is present in HashSet or not. If the value is not present in the HashSet then push the value in HashSet append the nodes in the new list , otherwise skip the value as it is the duplicate value.
Follow the steps below to solve the problem:
Initialize an empty HashSet and pointers new_head and tail as NULL.
Iterate through the original list, adding each unique node's value to the HashSet and appending the node to the new list.
Return the new_head of the new list with duplicates removed.
Below is the implementation of the above approach:
C++
// C++ Program to remove duplicates from a// sorted linked list using Hashset#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*removeDuplicates(Node*head){// Unordered map to track unique node valuesunordered_set<int>st;// Initialize pointers for traversing the original list// and building the new list without duplicatesNode*new_head=nullptr;Node*tail=nullptr;// Traverse the original listNode*curr=head;while(curr!=nullptr){// Check if the current node's data is not in the mapif(st.find(curr->data)==st.end()){// Create a new node for the unique dataNode*new_node=newNode(curr->data);// If new_head is null, this is the// first unique nodeif(new_head==nullptr){new_head=new_node;tail=new_head;}else{// Append the new node to the end// of the new listtail->next=new_node;tail=new_node;}// Mark this data as encounteredst.insert(curr->data);}// Move to the next node in the original listcurr=curr->next;}// Return the head of the new list with// duplicates removedreturnnew_head;}voidprintList(Node*node){while(node!=NULL){cout<<node->data<<" ";node=node->next;}cout<<endl;}intmain(){// Create a sorted linked list// 11->11->11->13->13->20Node*head=newNode(11);head->next=newNode(11);head->next->next=newNode(11);head->next->next->next=newNode(13);head->next->next->next->next=newNode(13);head->next->next->next->next->next=newNode(20);cout<<"Linked list before duplicate removal:"<<endl;printList(head);head=removeDuplicates(head);cout<<"Linked list after duplicate removal:"<<endl;printList(head);return0;}
Java
// Java program to remove duplicates from a// sorted linked list using Hashsetimportjava.io.*;importjava.util.HashSet;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to remove duplicatesstaticNoderemoveDuplicates(Nodehead){// HashSet to track unique node valuesHashSet<Integer>st=newHashSet<>();// Initialize pointers for traversing// the original list and building the new// list without duplicatesNodetemp=head;NodenewHead=null;Nodetail=null;// Traverse the original listwhile(temp!=null){// Check if the current node's data is not in// the setif(!st.contains(temp.data)){// Create a new node for the unique dataNodenewNode=newNode(temp.data);// If newHead is null, this is the first// unique nodeif(newHead==null){newHead=newNode;tail=newHead;}else{// Append the new node to the// end of the new listtail.next=newNode;tail=newNode;}// Mark this data as encounteredst.add(temp.data);}// Move to the next node in the original listtemp=temp.next;}// Return the head of the new list with// duplicates removedreturnnewHead;}// Function to print nodes in a given linked listpublicstaticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a sorted linked list:// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);System.out.println("Linked list before duplicate removal:");printList(head);head=removeDuplicates(head);System.out.println("Linked list after duplicate removal:");printList(head);}}
Python
# Python3 program to remove duplicate# nodes from a sorted linked list using HashsetclassNode:def__init__(self,x):self.data=xself.next=Nonedefremove_duplicates(head):# Set to track unique node valuesst=set()# Initialize pointers for traversing# the original list and building the # new list without duplicatestemp=headnew_head=Nonetail=None# Traverse the original listwhiletemp:# Check if the current node's data# is not in the setiftemp.datanotinst:# Create a new node for the unique datanew_node=Node(temp.data)# If new_head is None, this is the #first unique nodeifnew_headisNone:new_head=new_nodetail=new_headelse:# Append the new node to the end#of the new listtail.next=new_nodetail=new_node# Mark this data as encounteredst.add(temp.data)# Move to the next node in the original listtemp=temp.next# Return the head of the new list with#duplicates removedreturnnew_headdefprint_list(node):whilenode:print(node.data,end=" ")node=node.nextprint()if__name__=="__main__":# Create a sorted linked list:# 11->11->11->13->13->20head=Node(11)head.next=Node(11)head.next.next=Node(11)head.next.next.next=Node(13)head.next.next.next.next=Node(13)head.next.next.next.next.next=Node(20)print("Linked list before duplicate removal:")print_list(head)head=remove_duplicates(head)print("Linked list after duplicate removal:")print_list(head)
C#
// C# program to remove duplicates// from a sorted linked list using hashSetusingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to remove duplicatesstaticNodeRemoveDuplicates(Nodehead){// HashSet to track unique node valuesHashSet<int>st=newHashSet<int>();// Initialize pointers for traversing the original// list and building the new list without duplicatesNodetemp=head;NodenewHead=null;Nodetail=null;// Traverse the original listwhile(temp!=null){// Check if the current node's data// is not in the setif(!st.Contains(temp.data)){// Create a new node for the unique dataNodenewNode=newNode(temp.data);// If newHead is null, this is the// first unique nodeif(newHead==null){newHead=newNode;tail=newHead;}else{// Append the new node to the end// of the new listtail.next=newNode;tail=newNode;}// Mark this data as encounteredst.Add(temp.data);}// Move to the next node in the//original listtemp=temp.next;}// Return the head of the new listreturnnewHead;}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}Console.WriteLine();}staticvoidMain(){// Create a sorted linked list://11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);Console.WriteLine("Linked list before duplicate removal:");PrintList(head);head=RemoveDuplicates(head);Console.WriteLine("Linked list after duplicate removal:");PrintList(head);}}
JavaScript
// JavaScript program to remove duplicates// from a sorted linked list using hashSetclassNode{constructor(x){this.data=x;this.next=null;}}functionremoveDuplicates(head){// Set to track unique node valuesconstst=newSet();// Initialize pointers for traversing the original list// and building the new list without duplicateslettemp=head;letnewHead=null;lettail=null;// Traverse the original listwhile(temp!==null){// Check if the current node's// data is not in the setif(!st.has(temp.data)){// Create a new node for the unique dataconstnewNode=newNode(temp.data);// If newHead is null, this is the first// unique nodeif(newHead===null){newHead=newNode;tail=newHead;}else{// Append the new node to the end of// the new listtail.next=newNode;tail=newNode;}// Mark this data as encounteredst.add(temp.data);}// Move to the next node in the original listtemp=temp.next;}// Return the head of the new list with// duplicates removedreturnnewHead;}functionprintList(node){letcurrent=node;while(current){process.stdout.write(current.data+" ");current=current.next;}console.log();}// Create a sorted linked list:// 11->11->11->13->13->20lethead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);console.log("Linked list before duplicate removal:");printList(head);head=removeDuplicates(head);console.log("Linked list after duplicate removal:");printList(head);
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)
[Expected Approach] By Changing Next Pointer – O(n) Time and O(1) Space:
The idea is to traverse the linked list and for each node, if the next node has the same data, skip and delete the duplicate node.
Follow the steps below to solve the problem:
Traverse the linked list starting from the head node.
Iterate through the list, comparing each node with the next node.
If the data in the next node is same as the curr node adjust pointers to skip the next node.
Below is the implementation of the above approach:
C++
// C++ Program to remove duplicates from a// sorted linked list#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*removeDuplicates(Node*head){Node*curr=head;// Traverse the listwhile(curr!=NULL&&curr->next!=NULL){// Check if next value is same as currentif(curr->data==curr->next->data){Node*next_next=curr->next->next;curr->next=next_next;}elsecurr=curr->next;}returnhead;}voidprintList(Node*node){while(node!=NULL){cout<<node->data<<" ";node=node->next;}cout<<endl;}intmain(){// Create a sorted linked list// 11->11->11->13->13->20Node*head=newNode(11);head->next=newNode(11);head->next->next=newNode(11);head->next->next->next=newNode(13);head->next->next->next->next=newNode(13);head->next->next->next->next->next=newNode(20);cout<<"Linked list before duplicate removal:"<<endl;printList(head);head=removeDuplicates(head);cout<<"Linked list after duplicate removal:"<<endl;printList(head);return0;}
C
// C Program to remove duplicates from a // sorted linked list#include<stdio.h>structNode{intdata;structNode*next;};// Function to remove duplicatesstructNode*removeDuplicates(structNode*head){structNode*curr=head;// Traverse the listwhile(curr!=NULL&&curr->next!=NULL){// Check if next value is the same as currif(curr->data==curr->next->data){structNode*next_next=curr->next->next;curr->next=next_next;}elsecurr=curr->next;}returnhead;}voidprintList(structNode*node){while(node!=NULL){printf("%d ",node->data);node=node->next;}printf("\n");}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}intmain(){// Create a sorted linked list:// 11->11->11->13->13->20structNode*head=createNode(11);head->next=createNode(11);head->next->next=createNode(11);head->next->next->next=createNode(13);head->next->next->next->next=createNode(13);head->next->next->next->next->next=createNode(20);printf("Linked list before duplicate removal:\n");printList(head);head=removeDuplicates(head);printf("Linked list after duplicate removal:\n");printList(head);return0;}
Java
// Java program to remove duplicates// from a sorted linked listimportjava.io.*;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to remove duplicatesstaticNoderemoveDuplicates(Nodehead){Nodecurr=head;// Traverse the listwhile(curr!=null&&curr.next!=null){// Check if next value is the same as currif(curr.data==curr.next.data){NodenextNext=curr.next.next;curr.next=nextNext;}else{curr=curr.next;}}returnhead;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a sorted linked list:// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);System.out.println("Linked list before duplicate removal:");printList(head);head=removeDuplicates(head);System.out.println("Linked list after duplicate removal:");printList(head);}}
Python
# Python3 program to remove duplicate# nodes from a sorted linked listclassNode:def__init__(self,x):self.data=xself.next=Nonedefremove_duplicates(head):curr=head# Traverse the listwhilecurrandcurr.next:# Check if next value is the same as currifcurr.data==curr.next.data:next_next=curr.next.nextcurr.next=next_nextelse:curr=curr.nextreturnheaddefprint_list(node):whilenode:print(node.data,end=" ")node=node.nextprint()if__name__=="__main__":# Create a sorted linked list:# 11->11->11->13->13->20head=Node(11)head.next=Node(11)head.next.next=Node(11)head.next.next.next=Node(13)head.next.next.next.next=Node(13)head.next.next.next.next.next=Node(20)print("Linked list before duplicate removal:")print_list(head)head=remove_duplicates(head)print("Linked list after duplicate removal:")print_list(head)
C#
// C# program to remove duplicates// from a sorted linked listusingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to remove duplicatesstaticNodeRemoveDuplicates(Nodehead){Nodecurr=head;// Traverse the listwhile(curr!=null&&curr.next!=null){// Check if next value is the same as currif(curr.data==curr.next.data){NodenextNext=curr.next.next;curr.next=nextNext;}else{curr=curr.next;}}returnhead;}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}Console.WriteLine();}staticvoidMain(){// Create a sorted linked list:// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);Console.WriteLine("Linked list before duplicate removal:");PrintList(head);head=RemoveDuplicates(head);Console.WriteLine("Linked list after duplicate removal:");PrintList(head);}}
JavaScript
// JavaScript program to remove duplicates// from a sorted linked listclassNode{constructor(x){this.data=x;this.next=null;}}functionremoveDuplicates(head){letcurr=head;// Traverse the listwhile(curr&&curr.next){// Check if next value is the same as currif(curr.data===curr.next.data){letnextNext=curr.next.next;curr.next=nextNext;}else{curr=curr.next;}}returnhead;}functionprintList(node){letcurrent=node;while(current){process.stdout.write(current.data+" ");current=current.next;}console.log();}// Create a sorted linked list:// 11->11->11->13->13->20lethead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);console.log("Linked list before duplicate removal:");printList(head);head=removeDuplicates(head);console.log("Linked list after duplicate removal:");printList(head);
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)
[Alternate Approach] Using Recursion – O(n) Time and O(n) Space:
The idea is similar to the iterative approach. Here we are using the recursion to check each node and its next for duplicates. Please note that the iterative approach would be better in terns of time and space. The recursive approach can be good fun exercise or a question in an interview / exam.
Follow the steps below to solve the problem:
If the curr node or its next node is NULL, return the curr node.
If the current node’s data equals the next node’s data, adjust pointers to skip the duplicate.
If no duplicate, recursively process the next node.
Below is the implementation of the above approach:
C++
// C++ Program to remove duplicates from a// sorted linked list#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};// Function to remove duplicatesvoidremoveDuplicates(Node*head){// Base case: if the list is empty, returnif(head==NULL)return;// Check if the next node existsif(head->next!=NULL){// If current node has duplicate// data with the next nodeif(head->data==head->next->data){head->next=head->next->next;removeDuplicates(head);}else{removeDuplicates(head->next);}}}voidprintList(Node*node){while(node!=NULL){cout<<node->data<<" ";node=node->next;}cout<<endl;}intmain(){// Create a sorted linked list// 11->11->11->13->13->20Node*head=newNode(11);head->next=newNode(11);head->next->next=newNode(11);head->next->next->next=newNode(13);head->next->next->next->next=newNode(13);head->next->next->next->next->next=newNode(20);cout<<"Linked list before duplicate removal:"<<endl;printList(head);removeDuplicates(head);cout<<"Linked list after duplicate removal:"<<endl;printList(head);return0;}
C
// C Program to remove duplicates from a// sorted linked list#include<stdio.h>structNode{intdata;structNode*next;};structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}// Function to remove duplicatesvoidremoveDuplicates(structNode*head){// Base case: if the list is empty, returnif(head==NULL)return;// Check if the next node existsif(head->next!=NULL){// If current node has duplicate data// with the next nodeif(head->data==head->next->data){head->next=head->next->next;removeDuplicates(head);}elseremoveDuplicates(head->next);}}voidprintList(structNode*node){while(node!=NULL){printf("%d ",node->data);node=node->next;}printf("\n");}intmain(){// Create a sorted linked list:// 11->11->11->13->13->20structNode*head=createNode(11);head->next=createNode(11);head->next->next=createNode(11);head->next->next->next=createNode(13);head->next->next->next->next=createNode(13);head->next->next->next->next->next=createNode(20);printf("Linked list before duplicate removal:\n");printList(head);removeDuplicates(head);printf("Linked list after duplicate removal:\n");printList(head);return0;}
Java
// Java program to remove duplicates// from a sorted linked listimportjava.io.*;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to remove duplicatesstaticvoidremoveDuplicates(Nodehead){// Base case: if the list is empty, returnif(head==null)return;// Check if the next node existsif(head.next!=null){// If current node has duplicate data with the// next nodeif(head.data==head.next.data){head.next=head.next.next;removeDuplicates(head);}else{// Continue with next noderemoveDuplicates(head.next);}}}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a sorted linked list:// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);System.out.println("Linked list before duplicate removal:");printList(head);removeDuplicates(head);System.out.println("Linked list after duplicate removal:");printList(head);}}
Python
# Python3 program to remove duplicate# nodes from a sorted linked listclassNode:def__init__(self,x):self.data=xself.next=Nonedefremove_duplicates(head):# Base case: if the list is empty, returnifheadisNone:return# Check if the next node existsifhead.nextisnotNone:# If current node has duplicate data with the next nodeifhead.data==head.next.data:head.next=head.next.nextremove_duplicates(head)else:# Continue with next noderemove_duplicates(head.next)defprint_list(node):whilenode:print(node.data,end=" ")node=node.nextprint()if__name__=="__main__":# Create a sorted linked list:# 11->11->11->13->13->20head=Node(11)head.next=Node(11)head.next.next=Node(11)head.next.next.next=Node(13)head.next.next.next.next=Node(13)head.next.next.next.next.next=Node(20)print("Linked list before duplicate removal:")print_list(head)remove_duplicates(head)print("Linked list after duplicate removal:")print_list(head)
C#
// C# program to remove duplicates from a sorted linked listusingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to remove duplicatesstaticvoidRemoveDuplicates(Nodehead){// Base case: if the list is empty, returnif(head==null)return;// Check if the next node existsif(head.next!=null){// If current node has duplicate data with// the next nodeif(head.data==head.next.data){head.next=head.next.next;RemoveDuplicates(head);}else{// Continue with next nodeRemoveDuplicates(head.next);}}}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}Console.WriteLine();}staticvoidMain(){// Create a sorted linked list:// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);Console.WriteLine("Linked list before duplicate removal:");PrintList(head);RemoveDuplicates(head);Console.WriteLine("Linked list after duplicate removal:");PrintList(head);}}
JavaScript
// JavaScript program to remove duplicates from a sorted// linked listclassNode{constructor(x){this.data=x;this.next=null;}}functionremoveDuplicates(head){// Base case: if the list is empty, returnif(head===null)return;// Check if the next node existsif(head.next!==null){// If current node has duplicate data// with the next nodeif(head.data===head.next.data){head.next=head.next.next;removeDuplicates(head);}else{// Continue with next noderemoveDuplicates(head.next);}}}functionprintList(node){letcurrent=node;while(current){process.stdout.write(current.data+" ");current=current.next;}console.log();}// Create a sorted linked list:// 11->11->11->13->13->20lethead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);console.log("Linked list before duplicate removal:");printList(head);removeDuplicates(head);console.log("Linked list after duplicate removal:");printList(head);
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)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.