Last active
August 29, 2015 14:22
-
-
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?
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
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