Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Remove duplicate nodes with the use of a HashMap array
...
// Node class
static class Node {
int data;
Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
static Node removeDuplicates(Node head){
// null check here
if(head == null || head.next == null) return head;
// create a temporary node
Node next = head;
// create HashMap array
HashMap<Integer, Integer> map = new HashMap<>();
// insert node in map
map.put(next.data, 1);
// iterate list and insert rest of nodes in map
while(next.next != null){
// check if node already exists in map
if(!map.containsKey(next.next.data)){
map.put(next.next.data, 1);
next = next.next;
} else {
next.next = next.next.next;
}
}
// return the head of list
return head;
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment