题解 | #删除链表中重复的结点#
删除链表中重复的结点
http://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
import java.util.HashMap;
import java.util.Queue;
import java.util.LinkedList;
import java.util.HashSet; // 引入 HashSet 类
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
HashMap<Integer, Integer> hp = new HashMap<Integer, Integer>();
Queue<ListNode> q = new LinkedList<ListNode>();
while(pHead!=null){
Integer cnt = hp.get(pHead.val);
if(cnt==null) hp.put(pHead.val,1);
else hp.put(pHead.val,cnt+1);
q.offer(pHead);
pHead = pHead.next;
}
ListNode t;
ListNode ans = new ListNode(-1);
ListNode p = ans;
while(q.size()>0){
t = q.poll();
t.next = null;
// System.out.println(t.val + "" + hp.get(t.val));
if(hp.get(t.val)==1){
p.next = t;
p = p.next;
}
}
return ans.next;
}
}
出错的数据:1,1,2,3,3,4,5,5 如果放入队列的时候不把next置为null,那么 2连到4后,后面的5,5也会连上 因此需要每次放入或拿出来的时候,将其变为独立的节点 next变成null