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?
A:
Using hash table
(没想到,或者想到了,但是以前没有做过,故而不知道去搞)
public static void deleteDuplicates(LinkList list){
Hashtable table = new Hashtable();
Node pointer = list.head;
Node prePointer = null;
while(pointer != null){
if(table.containsKey(pointer.data))
prePointer.next = pointer.next;
else{
table.put(pointer.data, true);
}
prePointer = pointer;
pointer = pointer.getNext();
}
}
public static void deleteDuplicatesNoBuffer(LinkList list){
// use two pointers to delete duplicates
Node curPointer = list.head;
Node runner = null;
Node preRunner = null;
while(curPointer != null){
preRunner = curPointer;
runner = curPointer.next;
// check if all has the same value
while(runner!= null){
if(runner.data == curPointer.data){
// delete the at position runner.
preRunner.next = runner.next;
}else{
preRunner = runner;
}
runner = runner.next;
}
curPointer = curPointer.next;
}
}
Mistakes:
经常忘记,update指针,使之指向下一个位置。 1: 在list iterate的时候,
No comments:
Post a Comment