Removing Duplicates from an Unsorted Linked List (Without Extra Space)
If extra space is not allowed, we use two loops:
- The outer loop picks elements one by one.
- The inner loop removes duplicate occurrences.
Implementation
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class RemoveDuplicatesNoExtraSpace {
public static void removeDuplicates(Node head) {
Node current = head;
while (current != null) {
Node runner = current;
while (runner.next != null) {
if (runner.next.data == current.data) {
runner.next = runner.next.next; // Remove duplicate
} else {
runner = runner.next;
}
}
current = current.next;
}
}
public static void printList(Node head) {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head = new Node(4);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(3);
head.next.next.next.next = new Node(2);
System.out.println("Before removing duplicates:");
printList(head);
removeDuplicates(head);
System.out.println("After removing duplicates:");
printList(head);
}
}
Comments
Post a Comment