How to Remove Duplicate Elements From Java LinkedList?
Last Updated :
14 May, 2021
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
Example:
Initial composition :
7 2 3 3 2 7 6 2
After removing duplicates :
7 2 3 6
Pictorial Representation : ( a node in a LinkedList has two parts : data and link to next node (null in case of the last element)
Algorithm :
- Initially, a new node is created which points to the head.
- A temp node will point to current and index node will point to current.next.
- If the data of the index node and the current node is same i.e if a duplicate element is found, temp.next is made to point to index.next i.e it skips the duplicate element.
- If the above condition is not satisfied, then the temp is made to point to the previous node of an index.
- Index node iterates until the end and steps 3 and 4 are repeated.
- Steps 2 to 5 are executed till the current node points to the end i.e reaches its end.
Below is the implementation of the above approach:
Java
import java.io.*;
class Node {
Node next;
int data;
public Node( int data)
{
this .data = data;
this .next = null ;
}
}
public class singlyLinkedList {
public Node head = null ;
public Node tail = null ;
public void add( int data)
{
Node newNode = new Node(data);
if (head == null ) {
head = newNode;
tail = newNode;
}
else {
tail.next = newNode;
tail = newNode;
}
}
public void removeDuplicates()
{
Node current = head, index = null , temp = null ;
if (head == null ) {
return ;
}
else {
while (current != null ) {
temp = current;
index = current.next;
while (index != null ) {
if (current.data == index.data) {
temp.next = index.next;
}
else {
temp = index;
}
index = index.next;
}
current = current.next;
}
}
}
public void print()
{
Node current = head;
if (head == null ) {
System.out.println(
"Empty list please insert some elements first" );
return ;
}
while (current != null ) {
System.out.print(current.data + " " );
current = current.next;
}
System.out.println();
}
public static void main(String[] args)
{
singlyLinkedList List = new singlyLinkedList();
List.add( 9 );
List.add( 1 );
List.add( 1 );
List.add( 3 );
List.add( 4 );
List.add( 8 );
List.add( 2 );
List.add( 1 );
System.out.println( "Initial composition : " );
List.print();
List.removeDuplicates();
System.out.println( "After removing duplicates : " );
List.print();
}
}
|
Output
Initial composition :
9 1 1 3 4 8 2 1
After removing duplicates :
9 1 3 4 8 2
Time Complexity: O(N2)
Share your thoughts in the comments
Please Login to comment...