Created
June 18, 2014 08:47
-
-
Save chouclee/eba793a770b25674ad78 to your computer and use it in GitHub Desktop.
[CC150][2.1] Write code to remove duplicates from an unsorted linked list.
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.LinkedList; | |
import java.util.HashSet; | |
public class rmDuplicate { | |
//* why return a new LinkedList rather than modifiying the original one? | |
//* remove(object) in LinkedList(Java) could be O(N) in worst case (i.e. closer to tail of the LinkedList) | |
//* for LinkedList [1,1,...,1,1,1] (length N), remove dupicate elements would cost (1+2+...+N-1) ~ O(N^2) | |
//* write your own LinkedList where you can manipulate the reference could solve the problem | |
public static<Item> LinkedList<Item> rm (LinkedList<Item> list) { | |
HashSet<Item> set = new HashSet<Item>(); | |
LinkedList<Item> newList = new LinkedList<Item>(); | |
for (Item item : list) | |
if (set.add(item)) | |
newList.add(item); | |
return newList; | |
} | |
public static void main (String[] args) { | |
LinkedList<Integer> testA = new LinkedList<Integer>(); | |
for (int i = 0; i < 5; i++) | |
testA.add(i); | |
for (int i = 10; i > 0; i--) | |
testA.add(i); | |
System.out.println(testA.toString()); | |
System.out.println(rmDuplicate.rm(testA).toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment