import java.util.HashSet;
public class SinglyLinkedList {
// Node class
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// Head of the linked list
Node head;
// Method to add a node to the end of the list
public void addLast(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// Method to remove duplicates from the list
public void removeDuplicates() {
HashSet<Integer> set = new HashSet<>();
Node current = head;
Node previous = null;
while (current != null) {
if (set.contains(current.data)) {
previous.next = current.next;
} else {
set.add(current.data);
previous = current;
}
current = current.next;
}
}
// Method to display the list
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addLast(2);
list.addLast(4);
list.addLast(1);
System.out.println("Before removing duplicates:");
list.display();
list.removeDuplicates();
System.out.println("\nAfter removing duplicates:");
list.display();
}
}
Before removing duplicates:
1 2 3 2 4 1
After removing duplicates:
1 2 3 4
Node
class to represent a node in the linked list. Each node contains an integer data
and a reference to the next node in the list. The SinglyLinkedList
class contains a reference to the head of the list, a method to add a node to the end of the list, a method to remove duplicates from the list using a HashSet
, and a method to display the list.addLast
method, a new node is created with the specified data. If the list is empty (i.e. the head is null
), the new node becomes the head of the list. Otherwise, the method traverses the list starting from the head, and finds the last node. The next
field of the last node is set to the new node, making it the new last node.removeDuplicates
method, a HashSet
is used to keep track of the unique elements seen so far in the list. The method traverses the list starting from the head, and for each node, it checks if the HashSet
already contains its data
. If it does, the previous node's next
field is set to the current node's next
field, effectively removing the current node from the list. If it doesn't, the current node's data
is added to the HashSet
, and the previous node is updated to be the current node.display
method, the method traverses the list starting from the head, and prints the data of each node.main
method, the program creates a new SinglyLinkedList object, adds some nodes to the list, displays the list before removing duplicates.