In this article we are going to see how we remove duplicate elements from a singly linked list by using Java programming language.
Java Program to Remove Duplicate Elements from a Singly Linked List
Approach:
- Create a linked list.
- Add some elements(with duplicates) to it.
- Print the list.
- Call the user defined method
removeDup( )that iterates the whole list repeatedly and removes all the duplicate nodes from the list. - Display the new list.
Program:
import java.util.*;
// Main class
public class Main
{
// Class Node that defines the two linked list variables
class Node
{
int data;
Node nextNode;
// constructor to create a node
public Node(int data)
{
this.data = data;
this.nextNode = null;
}
}
// Setting the head and end of the node as NULL
public Node head = null;
public Node tail = null;
// Method to remove duplicate elements from a linked list
public void removeDup()
{
Node curr = head, index = null, temp = null;
if(head == null)
{
System.out.println("THe linked list is empty");
return;
}
else
{
while(curr != null)
{
//Node temp points to previous node to index.
temp = curr;
//Index points to the next node
index = curr.nextNode;
while(index != null)
{
//If curr node's data is equal to index node's data
if(curr.data == index.data)
{
//If we find a duplicate node it skips the duplicate node by pointing to nextNode node
temp.nextNode = index.nextNode;
}
else
{
//Temp points to the previous node in the index
temp = index;
}
index = index.nextNode;
}
curr = curr.nextNode;
}
}
}
// method to add a node to the end of the linked list
public void add(int data)
{
Node newNode = new Node(data);
// Checks if there was any previous node
if(head==null)
{
head = newNode;
tail = newNode;
}
else
{
tail.nextNode = newNode;
tail = newNode;
}
}
// Method to display all the nodes of the linked list
public void show()
{
Node curr = head;
// If the head is pointing to no node then the linked list is empty
if(head==null)
System.out.println("Linked List is empty");
else
{
System.out.println("The nodes are:");
while(curr!=null)
{
System.out.print(curr.data+",");
curr = curr.nextNode;
}
System.out.println();
}
}
public static void main(String[] args)
{
// create an object of the main class
Main ll = new Main();
// add elements to the linked list
ll.add(10);
ll.add(20);
ll.add(30);
ll.add(40);
ll.add(50);
ll.add(20);
ll.add(40);
// display the nodes
ll.show();
System.out.println("Removing the duplicate nodes...");
ll.removeDup();
// display the nodes
ll.show();
}
}
Output: The nodes are: 10,20,30,40,50,20,40, Removing the duplicate nodes... The nodes are: 10,20,30,40,50,
Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.