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().
Java
/* C++ Program to remove duplicates from a sorted linked list */
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
classNode
{
public:
intdata;
Node* next;
};
/* The function removes duplicates from a sorted list */
voidremoveDuplicates(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;
}
else/* This is tricky: only advance if no deletion */
{
current = current->next;
}
}
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the linked list */
voidpush(Node** head_ref, intnew_data)
{
/* allocate node */
Node* new_node = newNode();
/* 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 */
voidprintList(Node *node)
{
while(node!=NULL)
{
cout<<" "<<node->data;
node = node->next;
}
}
/* Driver program to test above functions*/
intmain()
{
/* 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<<"\nLinked list after duplicate removal ";
printList(head);
return0;
}
// This code is contributed by rathbhupendra
C
/* C Program to remove duplicates from a sorted linked list */
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
structNode
{
intdata;
structNode* next;
};
/* The function removes duplicates from a sorted list */
voidremoveDuplicates(structNode* head)
{
/* Pointer to traverse the linked list */
structNode* current = head;
/* Pointer to store the next pointer of a node to be deleted*/
structNode* 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;
}
else/* This is tricky: only advance if no deletion */
{
current = current->next;
}
}
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the linked list */
voidpush(structNode** head_ref, intnew_data)
{
/* allocate node */
structNode* new_node =
(structNode*) malloc(sizeof(structNode));
/* 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 */
voidprintList(structNode *node)
{
while(node!=NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
/* Driver program to test above functions*/
intmain()
{
/* Start with the empty list */
structNode* 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);
printf("\n Linked list before duplicate removal ");
printList(head);
/* Remove duplicates from linked list */
removeDuplicates(head);
printf("\n Linked list after duplicate removal ");
printList(head);
return0;
}
Java
// Java program to remove duplicates from a sorted linked list
classLinkedList
{
Node head; // head of list
/* Linked list Node*/
classNode
{
intdata;
Node next;
Node(intd) {data = d; next = null; }
}
voidremoveDuplicates()
{
/*Another reference to head*/
Node curr = head;
/* Traverse list till the last node */
while(curr != null) {
Node temp = curr;
/*Compare current node with the next node and
keep on deleting them until it matches the current
node data */
while(temp!=null&& temp.data.equals(curr.data)) {
temp = temp.next;
}
/*Set current node next to the next different
element denoted by temp*/
curr.next = temp;
curr = curr.next;
}
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
publicvoidpush(intnew_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = newNode(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;
}
/* Function to print linked list */
voidprintList()
{
Node temp = head;
while(temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
/* Driver program to test above functions */
publicstaticvoidmain(String args[])
{
LinkedList llist = newLinkedList();
llist.push(20);
llist.push(13);
llist.push(13);
llist.push(11);
llist.push(11);
llist.push(11);
System.out.println("List before removal of duplicates");
llist.printList();
llist.removeDuplicates();
System.out.println("List after removal of elements");
llist.printList();
}
}
/* This code is contributed by Rajat Mishra */
Python3
# Python3 program to remove duplicate
# nodes from a sorted linked list
# Node class
classNode:
# Constructor to initialize
# the node object
def__init__(self, data):
self.data =data
self.next=None
classLinkedList:
# Function to initialize head
def__init__(self):
self.head =None
# Function to insert a new node
# at the beginning
defpush(self, new_data):
new_node =Node(new_data)
new_node.next=self.head
self.head =new_node
# Given a reference to the head of a
# list and a key, delete the first
# occurrence of key in linked list
defdeleteNode(self, key):
# Store head node
temp =self.head
# If head node itself holds the
# key to be deleted
if(temp isnotNone):
if(temp.data ==key):
self.head =temp.next
temp =None
return
# Search for the key to be deleted,
# keep track of the previous node as
# we need to change 'prev.next'
while(temp isnotNone):
iftemp.data ==key:
break
prev =temp
temp =temp.next
# if key was not present in
# linked list
if(temp ==None):
return
# Unlink the node from linked list
prev.next=temp.next
temp =None
# Utility function to print the
# linked LinkedList
defprintList(self):
temp =self.head
while(temp):
print(temp.data , end =' ')
temp =temp.next
# This function removes duplicates
# from a sorted list
defremoveDuplicates(self):
temp =self.head
iftemp isNone:
return
whiletemp.nextisnotNone:
iftemp.data ==temp.next.data:
new =temp.next.next
temp.next=None
temp.next=new
else:
temp =temp.next
returnself.head
# Driver Code
llist =LinkedList()
llist.push(20)
llist.push(13)
llist.push(13)
llist.push(11)
llist.push(11)
llist.push(11)
print("Created Linked List: ")
llist.printList()
print()
print("Linked List after removing",
"duplicate elements:")
llist.removeDuplicates()
llist.printList()
# This code is contributed by
# Dushyant Pathak.
C#
// C# program to remove duplicates
// from a sorted linked list
usingSystem;
publicclassLinkedList
{
Node head; // head of list
/* Linked list Node*/
classNode
{
publicintdata;
publicNode next;
publicNode(intd)
{
data = d; next = null;
}
}
voidremoveDuplicates()
{
/*Another reference to head*/
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(head == null)
return;
/* Traverse list till the last node */
while(current.next != null)
{
/*Compare current node with the next node */
if(current.data == current.next.data)
{
next_next = current.next.next;
current.next = null;
current.next = next_next;
}
else// advance if no deletion
current = current.next;
}
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
publicvoidpush(intnew_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = newNode(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;
}
/* Function to print linked list */
voidprintList()
{
Node temp = head;
while(temp != null)
{
Console.Write(temp.data+" ");
temp = temp.next;
}
Console.WriteLine();
}
/* Driver code */
publicstaticvoidMain(String []args)
{
LinkedList llist = newLinkedList();
llist.push(20);
llist.push(13);
llist.push(13);
llist.push(11);
llist.push(11);
llist.push(11);
Console.WriteLine("List before removal of duplicates");
llist.printList();
llist.removeDuplicates();
Console.WriteLine("List after removal of elements");
llist.printList();
}
}
/* This code is contributed by 29AjayKumar */
Javascript
<script>
// Javascript program to remove duplicates from a sorted linked list
/* Linked list Node*/
class Node
{
constructor(d) {
this.data = d;
this.next = null;
}
}
let head=newNode(); // head of list
functionremoveDuplicates()
{
/*Another reference to head*/
let curr = head;
/* Traverse list till the last node */
while(curr != null) {
let temp = curr;
/*Compare current node with the next node and
keep on deleting them until it matches the current
node data */
while(temp!=null&& temp.data==curr.data) {
temp = temp.next;
}
/*Set current node next to the next different
element denoted by temp*/
curr.next = temp;
curr = curr.next;
}
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
functionpush(new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
let new_node = newNode(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;
}
/* Function to print linked list */
functionprintList()
{
let temp = head;
while(temp != null&& temp.data)
{
document.write(temp.data+" ");
temp = temp.next;
}
document.write("<br>");
}
/* Driver program to test above functions */
push(20)
push(13)
push(13)
push(11)
push(11)
push(11)
document.write("List before removal of duplicates ");
printList();
removeDuplicates();
document.write("List after removal of elements ");
printList();
// This code is contributed by unknown2108
</script>
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.
Space Complexity: O(1) , as there is no extra space used.
Recursive Approach :
C++
/* C++ Program to remove duplicates
from a sorted linked list */
#include <bits/stdc++.h>
usingnamespacestd;
/* Link list node */
classNode
{
public:
intdata;
Node* next;
};
/* The function removes duplicates
from a sorted list */
voidremoveDuplicates(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);
}
else/* This is tricky: only
advance if no deletion */
{
removeDuplicates(head->next);
}
}
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the
beginning of the linked list */
voidpush(Node** head_ref, intnew_data)
{
/* allocate node */
Node* new_node = newNode();
/* 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 */
voidprintList(Node *node)
{
while(node!=NULL)
{
cout<<" "<<node->data;
node = node->next;
}
}
/* Driver code*/
intmain()
{
/* 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<<"\nLinked list after duplicate removal ";
printList(head);
return0;
}
// This code is contributed by Ashita Gupta
C
/* C recursive Program to remove duplicates from a sorted linked list */
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
structNode
{
intdata;
structNode* next;
};
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the linked list */
voidpush(structNode** head_ref, intnew_data)
{
/* allocate node */
structNode* new_node =
(structNode*) malloc(sizeof(structNode));
/* 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 */
voidprintList(structNode *node)
{
while(node!=NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
Node* deleteDuplicates(Node* head) {
if(head == nullptr) returnnullptr;
if(head->next == nullptr) returnhead;
if(head->data == head->next->data) {
Node *tmp;
// If find next element duplicate, preserve the next pointer to be deleted,
// skip it, and then delete the stored one. Return head
tmp = head->next;
head->next = head->next->next;
free(tmp);
returndeleteDuplicates(head);
}
else{
// if doesn't find next element duplicate, leave head
// and check from next element
head->next = deleteDuplicates(head->next);
returnhead;
}
}
intmain()
{
/* Start with the empty list */
structNode* 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);
printf("\n Linked list before duplicate removal ");
printList(head);
/* Remove duplicates from linked list */
head = deleteDuplicates(head);
printf("\n Linked list after duplicate removal ");
printList(head);
return0;
}
/* This code is contributed by Yogesh shukla */
Java
// Java Program to remove duplicates
// from a sorted linked list
classGFG
{
/* Link list node */
staticclassNode
{
intdata;
Node next;
};
// The function removes duplicates
// from a sorted list
staticNode 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)
returnnull;
/* 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;
removeDuplicates(head);
}
/* This is tricky: only advance if no deletion */
else
{
removeDuplicates(head.next);
}
}
returnhead;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning
of the linked list */
staticNode push(Node head_ref,
intnew_data)
{
/* allocate node */
Node new_node = newNode();
/* 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;
returnhead_ref;
}
/* Function to print nodes in a given linked list */
staticvoidprintList(Node node)
{
while(node != null)
{
System.out.print(" "+ node.data);
node = node.next;
}
}
/* Driver code*/
publicstaticvoidmain(String args[])
{
/* 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 */
head = push(head, 20);
head = push(head, 13);
head = push(head, 13);
head = push(head, 11);
head = push(head, 11);
head = push(head, 11);
System.out.println("Linked list before"+
" duplicate removal ");
printList(head);
/* Remove duplicates from linked list */
head = removeDuplicates(head);
System.out.println("\nLinked list after"+
" duplicate removal ");
printList(head);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 Program to remove duplicates
# from a sorted linked list
importmath
# Link list node
classNode:
def__init__(self,data):
self.data =data
self.next=None
# The function removes duplicates
# from a sorted list
defremoveDuplicates(head):
# Pointer to store the pointer of a node
# to be deleted to_free
# do nothing if the list is empty
if(head ==None):
return
# Traverse the list till last node
if(head.next!=None):
# 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)
returnhead
# UTILITY FUNCTIONS
# Function to insert a node at the
# beginning of the linked list
defpush(head_ref, new_data):
# allocate node
new_node =Node(new_data)
# 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
returnhead_ref
# Function to print nodes in a given linked list
defprintList(node):
while(node !=None):
print(node.data, end =" ")
node =node.next
# Driver code
if__name__=='__main__':
# Start with the empty list
head =None
# Let us create a sorted linked list
# to test the functions
# Created linked list will be 11.11.11.13.13.20
head =push(head, 20)
head =push(head, 13)
head =push(head, 13)
head =push(head, 11)
head =push(head, 11)
head =push(head, 11)
print("Linked list before duplicate removal ",
end ="")
printList(head)
# Remove duplicates from linked list
removeDuplicates(head)
print("\nLinked list after duplicate removal ",
end ="")
printList(head)
# This code is contributed by Srathore
C#
// C# Program to remove duplicates
// from a sorted linked list
usingSystem;
classGFG
{
/* Link list node */
publicclassNode
{
publicintdata;
publicNode next;
};
// The function removes duplicates
// from a sorted list
staticNode 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)
returnnull;
/* 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;
removeDuplicates(head);
}
/* This is tricky: only advance if no deletion */
else
{
removeDuplicates(head.next);
}
}
returnhead;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning
of the linked list */
staticNode push(Node head_ref,
intnew_data)
{
/* allocate node */
Node new_node = newNode();
/* 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;
returnhead_ref;
}
/* Function to print nodes in
a given linked list */
staticvoidprintList(Node node)
{
while(node != null)
{
Console.Write(" "+ node.data);
node = node.next;
}
}
// Driver code
publicstaticvoidMain(String []args)
{
/* 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 */
head = push(head, 20);
head = push(head, 13);
head = push(head, 13);
head = push(head, 11);
head = push(head, 11);
head = push(head, 11);
Console.Write("Linked list before"+
" duplicate removal ");
printList(head);
/* Remove duplicates from linked list */
head = removeDuplicates(head);
Console.Write("\nLinked list after"+
" duplicate removal ");
printList(head);
}
}
// This code is contributed by PrinciRaj1992
Javascript
<script>
// JavaScript Program to remove duplicates
// from a sorted linked list
/* Link list node */
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
// The function removes duplicates
// from a sorted list
functionremoveDuplicates(head) {
/*
Pointer to store the pointer
of a node to be deleted
*/
varto_free;
/* do nothing if the list is empty */
if(head == null)
returnnull;
/* 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;
removeDuplicates(head);
}
/* This is tricky: only advance
if no deletion */
else{
removeDuplicates(head.next);
}
}
returnhead;
}
/* UTILITY FUNCTIONS */
/*
Function to insert a node at
the beginning of the linked list
*/
functionpush(head_ref , new_data) {
/* allocate node */
varnew_node = newNode();
/* 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;
returnhead_ref;
}
/* Function to print nodes in a given linked list */
functionprintList(node) {
while(node != null) {
document.write(" "+ node.data);
node = node.next;
}
}
/* Driver code */
/* Start with the empty list */
varhead = null;
/*
Let us create a sorted linked list to
test the functions Created linked list
will be 11.11.11.13.13.20
*/
head = push(head, 20);
head = push(head, 13);
head = push(head, 13);
head = push(head, 11);
head = push(head, 11);
head = push(head, 11);
document.write("Linked list before"+
" duplicate removal <br/>");
printList(head);
/* Remove duplicates from linked list */
head = removeDuplicates(head);
document.write("<br/>Linked list after"+
" duplicate removal <br/>");
printList(head);
// This code is contributed by todaysgaurav
</script>
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)
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++14
// C++ program to remove duplicates
// from a sorted linked list
#include <bits/stdc++.h>
usingnamespacestd;
// Linked list Node
structNode {
intdata;
Node* next;
Node(intd)
{
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;
returnhead;
}
Node* push(Node* head, intnew_data)
{
/* 1 & 2: Allocate the Node & Put in the data*/
Node* new_node = newNode(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;
returnhead;
}
/* Function to print linked list */
voidprintList(Node* head)
{
Node* temp = head;
while(temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
/* Driver code */
intmain()
{
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\n");
printList(llist);
cout << ("List after removal of elements\n");
llist = removeDuplicates(llist);
printList(llist);
}
// This code is contributed by Sania Kumari Gupta
C
// C program to remove duplicates from a sorted linked list
#include <stdio.h>
#include <stdlib.h>
/* Link list node */
typedefstructNode {
intdata;
structNode* next;
} Node;
// 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;
returnhead;
}
voidpush(Node** head_ref, intnew_data)
{
/* allocate node */
Node* new_node = (Node*)malloc(sizeof(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 linked list */
voidprintList(Node* head)
{
Node* temp = head;
while(temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
/* Driver code */
intmain()
{
Node* llist = NULL;
push(&llist, 20);
push(&llist, 13);
push(&llist, 13);
push(&llist, 11);
push(&llist, 11);
push(&llist, 11);
printf("List before removal of duplicates\n");
printList(llist);
printf("List after removal of elements\n");
llist = removeDuplicates(llist);
printList(llist);
}
// This code is contributed by Sania Kumari Gupta
Java
// Java program to remove duplicates
// from a sorted linked list
classLinkedList {
// head of list
Node head;
// Linked list Node
classNode {
intdata;
Node next;
Node(intd)
{
data = d;
next = null;
}
}
// Function to remove duplicates from the given linked
// list
voidremoveDuplicates()
{
// 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;
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
publicvoidpush(intnew_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = newNode(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;
}
/* Function to print linked list */
voidprintList()
{
Node temp = head;
while(temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
/* Driver program to test above functions */
publicstaticvoidmain(String args[])
{
LinkedList llist = newLinkedList();
llist.push(20);
llist.push(13);
llist.push(13);
llist.push(11);
llist.push(11);
llist.push(11);
System.out.print("List before ");
System.out.println("removal of duplicates");
llist.printList();
llist.removeDuplicates();
System.out.println(
"List after removal of elements");
llist.printList();
}
}
// This code is contributed by Sania Kumari Gupta
Python3
# Python3 program to remove duplicates
# from a sorted linked list
importmath
# Link list node
classNode:
def__init__(self, data):
self.data =data
self.next=None
# The function removes duplicates
# from the given linked list
defremoveDuplicates(head):
# Do nothing if the list consist of
# only one element or empty
if(head ==Noneand
head.next==None):
return
# Construct a pointer
# pointing towards head
current =head
# Initialise a while loop till the
# second last node of the linkedlist
while(current.next):
# If the data of current and next
# node is equal we will skip the
# node between them
ifcurrent.data ==current.next.data:
current.next=current.next.next
# If the data of current and
# next node is different move
# the pointer to the next node
else:
current =current.next
return
# UTILITY FUNCTIONS
# Function to insert a node at the
# beginning of the linked list
defpush(head_ref, new_data):
# Allocate node
new_node =Node(new_data)
# 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
returnhead_ref
# Function to print nodes
# in a given linked list
defprintList(node):
while(node !=None):
print(node.data, end =" ")
node =node.next
# Driver code
if__name__=='__main__':
head =None
head =push(head, 20)
head =push(head, 13)
head =push(head, 13)
head =push(head, 11)
head =push(head, 11)
head =push(head, 11)
print("List before removal of "
"duplicates ", end ="")
printList(head)
removeDuplicates(head)
print("\nList after removal of "
"elements ", end ="")
printList(head)
# This code is contributed by MukulTomar
C#
// C# program to remove duplicates
// from a sorted linked list
usingSystem;
classLinkedList
{
// head of list
publicNode head;
// Linked list Node
publicclassNode
{
publicintdata;
publicNode next;
publicNode(intd) {
data = d;
next = null;
}
}
// Function to remove duplicates
// from the given linked list
voidremoveDuplicates()
{
// 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;
}
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
publicvoidpush(intnew_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = newNode(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;
}
/* Function to print linked list */
voidprintList()
{
Node temp = head;
while(temp != null)
{
Console.Write(temp.data + " ");
temp = temp.next;
}
Console.WriteLine();
}
/* Driver code */
publicstaticvoidMain(string[]args)
{
LinkedList llist = newLinkedList();
llist.push(20);
llist.push(13);
llist.push(13);
llist.push(11);
llist.push(11);
llist.push(11);
Console.Write("List before ");
Console.WriteLine("removal of duplicates");
llist.printList();
llist.removeDuplicates();
Console.WriteLine("List after removal of elements");
llist.printList();
}
}
// This code is contributed by rutvik_56
Javascript
<script>
// javascript program to remove duplicates
// from a sorted linked list
// head of list
varhead;
// Linked list Node
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
// Function to remove duplicates
// from the given linked list
functionremoveDuplicates() {
// Two references to head
// temp will iterate to the
// whole Linked List
// prev will point towards
// the first occurrence of every element
vartemp = 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;
}
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
functionpush(new_data) {
/*
* 1 & 2: Allocate the Node & Put in the data
*/
varnew_node = newNode(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;
}
/* Function to print linked list */
functionprintList() {
vartemp = head;
while(temp != null) {
document.write(temp.data + " ");
temp = temp.next;
}
document.write("<br/>");
}
/* Driver program to test above functions */
push(20);
push(13);
push(13);
push(11);
push(11);
push(11);
document.write("List before ");
document.write("removal of duplicates<br/>");
printList();
removeDuplicates();
document.write("List after removal of elements<br/>");
printList();
// This code contributed by aashish1995
</script>
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)
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++
// CPP program for the above approach
#include <bits/stdc++.h>
usingnamespacestd;
/* Link list node */
structNode {
intdata;
Node* next;
Node()
{
data = 0;
next = NULL;
}
};
/* Function to insert a node at
the beginning of the linked
* list */
voidpush(Node** head_ref, intnew_data)
{
/* allocate node */
Node* new_node = newNode();
/* 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 */
voidprintList(Node* node)
{
while(node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
// Function to remove duplicates
voidremoveDuplicates(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
intmain()
{
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 << "\nLinked list after duplicate removal ";
removeDuplicates(head);
return0;
}
// This code is contributed by yashbeersingh42
Java
// Java program for the above approach
importjava.io.*;
importjava.util.*;
classNode
{
intdata;
Node next;
Node()
{
data = 0;
next = null;
}
}
classGFG
{
/* Function to insert a node at
the beginning of the linked
* list */
staticNode push(Node head_ref, intnew_data)
{
/* allocate node */
Node new_node = newNode();
/* 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;
returnhead_ref;
}
/* Function to print nodes
in a given linked list */
staticvoidprintList(Node node)
{
while(node != null)
{
System.out.print(node.data + " ");
node = node.next;
}
}
// Function to remove duplicates
staticvoidremoveDuplicates(Node head)
{
HashMap<Integer, Boolean> track = newHashMap<>();
Node temp = head;
while(temp != null)
{
if(!track.containsKey(temp.data))
{
System.out.print(temp.data + " ");
}
track.put(temp.data , true);
temp = temp.next;
}
}
// Driver Code
publicstaticvoidmain (String[] args)
{
Node head = null;
/* Created linked list will be
11->11->11->13->13->20 */
head = push(head, 20);
head = push(head, 13);
head = push(head, 13);
head = push(head, 11);
head = push(head, 11);
head = push(head, 11);
System.out.print("Linked list before duplicate removal ");
printList(head);
System.out.print("\nLinked list after duplicate removal ");
removeDuplicates(head);
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python program for the above approach
classNode:
def__init__(self):
self.data =0;
self.next=None;
# Function to insert a node at
# the beginning of the linked list
defpush(head_ref, new_data):
# allocate node
new_node =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;
returnhead_ref;
# Function to print nodes in a given linked list
defprintList(node):
while(node !=None):
print(node.data, end=" ");
node =node.next;
# Function to remove duplicates
defremoveDuplicates(head):
track ={};
temp =head;
while(temp !=None):
if(nottemp.data intrack):
print(temp.data, end=" ");
track[temp.data] =True;
temp =temp.next;
# Driver Code
head =None;
# Created linked list will be 11->11->11->13->13->20
head =push(head, 20);
head =push(head, 13);
head =push(head, 13);
head =push(head, 11);
head =push(head, 11);
head =push(head, 11);
print("Linked list before duplicate removal ", end=" ");
printList(head);
print("\nLinked list after duplicate removal ", end=" ");
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