剑指offer07 JZ76 删除链表中重复的结点
删除链表中重复的结点
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&tqId=23450&ru=%2Fpractice%2F886370fe658f41b498d40fb34ae76ff9&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D13
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
Map<Integer,Integer> map=new HashMap<>();
ListNode cur=pHead;
//统计每个链表元素值的次数
while(cur!=null){
if(map.containsKey(cur.val)){
map.put(cur.val,(int)map.get(cur.val)+1);
}
else{
map.put(cur.val,1);
}
cur=cur.next;
}
ListNode res = new ListNode(0);
//在链表前加一个表头
res.next=pHead;//连接上
cur=res;
//再次遍历 将次数不等于1的给跳过
while(cur.next!=null){
if(map.get(cur.next.val)!=1){
//删除 修改指向
cur.next=cur.next.next;
}else{
//向下走
cur=cur.next;
}
}
return res.next;
}
}