编写代码,移除未排序链表中的重复节点。
进阶,
如果不得使用临时缓冲区,该怎么解决?
package test;
import java.util.HashSet;
public class RemoveDup {
//利用HashSet
public Node removeDup(Node head){
if(head==null || head.next==null)
return head;
Node newHead = new Node(0);
newHead.next = head;
Node point = newHead;
HashSet<Integer> set = new HashSet<Integer>();
while(point.next != null){
if(set.contains(point.next.val))
point.next = point.next.next;
else{
set.add(point.next.val);
point = point.next;
}
}
return newHead.next;
}
//不利用临时缓冲区
public Node removeDup(Node head){
if(head==null || head.next==null)
return head;
Node current = head;
while(current != null){
Node point = current;
whille(point.next != null){
if(point.next.val == current.val)
point.next = point.next.next;
else
point = point.next;
}
current = current.next;
}
return head;
}
}