Skip to content

Instantly share code, notes, and snippets.

@spininertia
Created March 2, 2013 06:48
Show Gist options
  • Save spininertia/5069966 to your computer and use it in GitHub Desktop.
Save spininertia/5069966 to your computer and use it in GitHub Desktop.
Career Cup 2.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?
package chapter2;
import java.util.HashSet;
/*
* Career Cup 2.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?
*/
public class C2P1 {
/*
* use a hash set to record existing value along with traversing the linked list
* time complexity: O(n)
* space complexity: O(n)
*/
public static void removeDuplicatesUsingBuffer(Node header){
HashSet<Integer> hashSet = new HashSet<Integer>();
Node prev = null;
while(header != null){
if(hashSet.contains(header.value))
prev.next = header.next;
else {
prev = header;
hashSet.add(header.value);
}
header = header.next;
}
}
/*
* traverse the linked list with a inner loop checking equality
* time complexity: O(n^2)
* space complexity: O(1)
*/
public static void removeDuplicatesNotUsingBuffer(Node header) {
Node prev, post;
while(header != null){
prev = header;
post = header.next;
while(post != null){
if(post.value == header.value){
prev.next = post.next;
}
else {
prev = post;
}
post = post.next;
}
header = header.next;
}
}
public static void main(String[] args) {
int[] array = {1,2,2,3,1,5,4,5};
Node header = new Node(array);
Node header1 = new Node(array);
header.printLinkList();
removeDuplicatesUsingBuffer(header);
header.printLinkList();
removeDuplicatesNotUsingBuffer(header1);
header1.printLinkList();
}
}
package chapter2;
public class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
this.next = null;
}
public Node(int[] array){
if (array.length != 0) {
this.value = array[0];
this.next = null;
}
for (int i = 1; i < array.length; i++) {
this.appendToTail(array[i]);
}
}
public void printLinkList(){
Node pointer = this;
while (pointer != null) {
System.out.printf("%d%s",pointer.value, pointer.next != null ? " -> ":"\n");
pointer = pointer.next;
}
}
public void appendToTail(int d) {
Node pointer = this;
Node node = new Node(d);
while(pointer.next != null){
pointer = pointer.next;
}
pointer.next = node;
}
@Override
public String toString(){
return String.format("value of node:%d", value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment