Java Program For Removing Duplicates From A Sorted Linked List
Last Updated :
25 Apr, 2023
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
// Java program to remove duplicates
// from a sorted linked list
class LinkedList
{
// Head of list
Node head;
// Linked list Node
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
void removeDuplicates()
{
// 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 == 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.
public void push(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;
}
// Function to print linked list
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
// Driver code
public static void main(String args[])
{
LinkedList llist = new LinkedList();
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
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) , as there is no extra space used.
Recursive Approach :
Java
// Java Program to remove duplicates
// from a sorted linked list
class GFG
{
// Link list node
static class Node
{
int data;
Node next;
};
// The function removes duplicates
// from a sorted list
static Node 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 null;
// 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);
}
}
return head;
}
// UTILITY FUNCTIONS
/* Function to insert a node at the
beginning of the linked list */
static Node 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 of the
// new node
new_node.next = (head_ref);
// Move the head to point to the
// new node
(head_ref) = new_node;
return head_ref;
}
// Function to print nodes in a given
// linked list
static void printList(Node node)
{
while (node != null)
{
System.out.print(" " + node.data);
node = node.next;
}
}
// Driver code
public static void main(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("Linked list after" +
" duplicate removal ");
printList(head);
}
}
// This code is contributed by Arnab Kundu
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:
Java
// Java program to remove duplicates
// from a sorted linked list
class LinkedList
{
// Head of list
Node head;
// Linked list Node
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
// Function to remove duplicates
// from the given linked list
void removeDuplicates()
{
// 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.
public void push(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;
}
// Function to print linked list
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
// Driver code
public static void main(String args[])
{
LinkedList llist = new LinkedList();
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 Arshita
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:
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class Node
{
int data;
Node next;
Node()
{
data = 0;
next = null;
}
}
class GFG
{
/* Function to insert a node at the
beginning of the linked list */
static Node 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 of
the new node */
new_node.next = (head_ref);
/* Move the head to point
to the new node */
head_ref = new_node;
return head_ref;
}
/* Function to print nodes
in a given linked list */
static void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.next;
}
}
// Function to remove duplicates
static void removeDuplicates(Node head)
{
HashMap<Integer, Boolean> track = new HashMap<>();
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
public static void main (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(
"Linked list after duplicate removal ");
removeDuplicates(head);
}
}
// This code is contributed by avanitrachhadiya2155
Output:
Linked list before duplicate removal 11 11 11 13 13 20
Linked list after duplicate removal 11 13 20
Time Complexity: O(Number of Nodes)
Space Complexity: O(Number of Nodes)
Please refer complete article on Remove duplicates from a sorted linked list for more details!
Similar Reads
Java Program For Removing Duplicates From An Unsorted Linked List
Given an unsorted Linked List, the task is to remove duplicates from the list. Examples: Input: linked_list = 12 -> 11 -> 12 -> 21 -> 41 -> 43 -> 21 Output: 12 -> 11 -> 21 -> 41 -> 43 Explanation: Second occurrence of 12 and 21 are removed. Input: linked_list = 12 ->
6 min read
Java 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 List Note that this is different from Rem
3 min read
Java 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
4 min read
Java Program for Reverse a linked list
Given a pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes. Examples: Input: Head of following linked list 1->2->3->4->NULLOutput: Linked list should be changed to, 4->3->2->1->NULL In
3 min read
Java Program For Writing A Function To Delete A Linked List
Algorithm For Java:In Java, automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null. Implementation: Java // Java program to delete a linked list class LinkedList { // Head of the list Node head; // Linked List node class Node { int data; Node next;
2 min read
Java 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
Java 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
Java 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
How to Remove Duplicate Elements From Java LinkedList?
Linked List is a part of the Collection in java.util package. LinkedList class is an implementation of the LinkedList data structure it is a linear data structure. In LinkedList due to the dynamical allocation of memory, insertions and deletions are easy processes. For removing duplicates from Examp
4 min read
Java Program For Flattening A Linked List
Given a linked list where every node represents a linked list and contains two pointers of its type: Pointer to next node in the main list (we call it 'right' pointer in the code below).Pointer to a linked list where this node is headed (we call it the 'down' pointer in the code below). All linked l
4 min read