2.1
package com.careercup.chapter2;
/*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.HashSet;
public class CareerCup_2_1 {
public static void removeDuplicate(LinkNode head){
HashSet<Integer> mySet = new HashSet<>();
mySet.add(head.getValue());
LinkNode current = head;
while(current.getNext() !=null){
if(mySet.contains(current.getNext().getValue())){//如果包含此元素则返回true
current.setNext(current.getNext().getNext());
}else{
mySet.add(current.getValue());
current = current.getNext();
}
}
}
public static void removeDuplicate_NoBuffer(LinkNode head){
LinkNode current =head;
while(current!=null){
LinkNode check = current;
while(check.getNext()!=null){
if(check.getValue() == check.getNext().getValue())
check.setNext(check.getNext().getNext());
else
check.setNext(check.getNext().getNext());
}
current = current.getNext();
}
}
}