题目描述
分析
一开始陷入了一个误区,上述的链表被我处理为了12345,只是去掉了重复的第二个元素,而题目要求是重复的节点都要去掉。那么简单的递归就不能解决问题了。首先,需要知道某个节点在全局出现了几次,再去连接。那么解决此题的第一步就是遍历链表,通过map记录节点的出现的频次。然后再从第一个节点开始进行连接。
遍历节点统计频次:
HashMap<Integer,Integer> map = new HashMap();
while(pHead != null) {
if(map.containsKey(pHead.val)) {
map.put(pHead.val,map.get(pHead.val)+1);
}else {
map.put(pHead.val,1);
}
pHead = pHead.next;
}
选择性连接:
public ListNode link(ListNode pHead) {
if(pHead == null) {
return null;
}
if(map.get(pHead.val) != 1) {
return link(pHead.next);
}else {
pHead.next = link(pHead.next);
return pHead;
}
}
完整代码
public class Solution {
HashMap<Integer,Integer> map = new HashMap();
public ListNode deleteDuplication(ListNode pHead)
{
ListNode node = pHead;
while(pHead != null) {
if(map.containsKey(pHead.val)) {
map.put(pHead.val,map.get(pHead.val)+1);
}else {
map.put(pHead.val,1);
}
pHead = pHead.next;
}
ListNode first = link(node);
return first;
}
public ListNode link(ListNode pHead) {
if(pHead == null) {
return null;
}
if(map.get(pHead.val) != 1) {
return link(pHead.next);
}else {
pHead.next = link(pHead.next);
return pHead;
}
}
}