題目
給定一個無序單鏈表的頭節點head,刪除其中值重複出現的節點。
原鏈表 | 刪除後 |
1->2->3->3->4->2->4->1 | 1->2->3->4 |
要求:
方法一:時間複雜度O(N)
方法二:額外空間複雜度O(1)
思路
方法一:利用哈希表
- 先將頭節點加入哈希表中
- 依次遍歷鏈表節點,每次先查看當前節點的值是否在哈希表中,如果在,就跳過當前節點,否則就加入哈希表中
源碼
public class Node{
public int value;
public Node next;
public Node(int data){
this.value=data;
}
}
public void removeRep1(Node head){
if(head==null){
return;
}
HashSet<Integer> set=new HashSet<Integer>();
Node pre=head;
Node cur=head.next;
set.add(head.value);
while(cur!=null){
if(set.contains(cur.value)){
pre.next=cur.next;
}else{
set.add(cur.value);
pre=cur;
}
cur=cur.next;
}
}