I have the following code for removing duplicates from a Linked list and it works perfectly fine. However I have some questions on how it works.
Node.java
public class Node {
int value;
Node next;
Node(int value) {
this.value = value;
this.next = null;
}
}
RemoveDuplicates.java
public class RemoveDuplicates {
public static void removeDups(Node head) {
Node p = null;
Set<Integer> set = new HashSet<>();
while(head != null) {
if(set.add(head.value)) {
p = head;
} else {
p.next = head.next;
}
head = head.next; // Shouldn't this set the input node (head) as null in the last iteration?
}
}
public static void main(String[] args) {
Node n1 = new Node(10);
Node n2 = new Node(11);
Node n3 = new Node(11);
Node n4 = new Node(10);
Node n5 = new Node(12);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
removeDups(n1); // Shouldn't n1 be null as we looped thru the end inside the method?
while(n1 != null) {
System.out.print(n1.value + " "); // Prints -> 10 11 12
n1 = n1.next;
}
System.out.println(n1 == null); // This returns true
}
}
- How does the head node still pointing correctly to the head when
looped thru inside the
removeDupsmethod? - On the other hand when we loop thru it inside the
mainmethod, it returns null?