Remove duplicate nodes with the use of a HashMap array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
// 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