Skip to content

Instantly share code, notes, and snippets.

@xnorcode
Last active August 29, 2018 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnorcode/6e2e5d2eb91a02324a485c6fb7ed86b0 to your computer and use it in GitHub Desktop.
Save xnorcode/6e2e5d2eb91a02324a485c6fb7ed86b0 to your computer and use it in GitHub Desktop.
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