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
class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
void removeDuplicates()
{
Node curr = head;
while (curr != null )
{
Node temp = curr;
while (temp != null &&
temp.data == curr.data)
{
temp = temp.next;
}
curr.next = temp;
curr = curr.next;
}
}
public void push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList()
{
Node temp = head;
while (temp != null )
{
System.out.print(temp.data+ " " );
temp = temp.next;
}
System.out.println();
}
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();
}
}
|
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
class GFG
{
static class Node
{
int data;
Node next;
};
static Node removeDuplicates(Node head)
{
Node to_free;
if (head == null )
return null ;
if (head.next != null )
{
if (head.data == head.next.data)
{
to_free = head.next;
head.next = head.next.next;
removeDuplicates(head);
}
else
{
removeDuplicates(head.next);
}
}
return head;
}
static Node push(Node head_ref,
int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
static void printList(Node node)
{
while (node != null )
{
System.out.print( " " + node.data);
node = node.next;
}
}
public static void main(String args[])
{
Node head = null ;
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);
head = removeDuplicates(head);
System.out.println( "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), 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
class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
void removeDuplicates()
{
Node temp = head,prev = head;
while (temp != null )
{
if (temp.data != prev.data)
{
prev.next = temp;
prev = temp;
}
temp = temp.next;
}
if (prev != temp)
{
prev.next = null ;
}
}
public void push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList()
{
Node temp = head;
while (temp != null )
{
System.out.print(temp.data + " " );
temp = temp.next;
}
System.out.println();
}
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();
}
}
|
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
import java.io.*;
import java.util.*;
class Node
{
int data;
Node next;
Node()
{
data = 0 ;
next = null ;
}
}
class GFG
{
static Node push(Node head_ref,
int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
head_ref = new_node;
return head_ref;
}
static void printList(Node node)
{
while (node != null )
{
System.out.print(node.data + " " );
node = node.next;
}
}
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;
}
}
public static void main (String[] args)
{
Node head = null ;
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);
}
}
|
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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
13 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Conditions to apply Binary Search Algorithm in a Data S
15+ min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
8 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read