Skip to content

Instantly share code, notes, and snippets.

@mogutou1214
Last active August 29, 2015 14:22
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 mogutou1214/e5a233231944ad32b50d to your computer and use it in GitHub Desktop.
Save mogutou1214/e5a233231944ad32b50d to your computer and use it in GitHub Desktop.
CC2.1 - Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed?
import java.util.Hashtable;
public class removeDuplicates {
public static void Solution(LinkedListNode head) {
if (head == null) return;
Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
LinkedListNode dummyHead = new LinkedListNode(0);
dummyHead.next = head;
LinkedListNode ptr = dummyHead;
while(ptr.next != null) {
if(!table.containsKey(ptr.next.val)) {
table.put(ptr.next.val, true);
ptr = ptr.next;
} else {
ptr.next = ptr.next.next;
}
}
}
public static void main(String[] args) {
LinkedListNode a = new LinkedListNode(3);
LinkedListNode b = new LinkedListNode(1);
LinkedListNode c = new LinkedListNode(1);
LinkedListNode d = new LinkedListNode(18);
LinkedListNode e = new LinkedListNode(1);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
a.printList();
removeDuplicates.Solution(a);
System.out.println();
a.printList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment