I am trying to delete duplicate nodes in an unsorted linked list. However, my output is not changing the linked list at all.
I tried to replace this code:
list.add(new Node(1));
list.add(new Node(2));
list.add(new Node(3));
list.add(new Node(1));
list.add(new Node(1));
with
Node firstNode = new Node(1);
Node secondNode = new Node(2);
Node thirdNode = new Node(3);
Node fourthNode = new Node(1);
Node fifthNode = new Node(1);
firstNode.next = secondNode;
secondNode.next = thirdNode;
thirdNode.next = fourthNode;
fourthNode.next = fifthNode;
list.add(firstNode);
list.add(secondNode);
list.add(thirdNode);
list.add(fourthNode);
list.add(fifthNode);
but still no luck.
import java.util.HashSet;
import java.util.LinkedList;
class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
class LinkedLists {
Node head;
public static void removeDups(Node n) {
HashSet<Integer> set = new HashSet<Integer>();
Node prev = null;
if (n == null) {
return;
}
while(n != null) {
if (set.contains(n.value)) {
prev.next = n.next;
} else {
set.add(n.value);
prev = n;
}
n = n.next;
}
}
public static void main(String[] args) {
LinkedList<Node> list = new LinkedList<Node>();
list.add(new Node(1));
list.add(new Node(2));
list.add(new Node(3));
list.add(new Node(1));
list.add(new Node(1));
removeDups(list.getFirst());
for (int i = 0; i < list.size(); ++i) {
System.out.print(list.get(i).value);
}
}
}
I expect an output of 123.