题目
解题注意事项
链表的题,需要理解指针,在很多语言中叫引用。做题过程中注意节点的边界,指针指向。
参考代码
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
if (head == null) return head;
Map<Integer, Integer> cnt = new HashMap<>(); //k: 节点值 v:出现次数
ListNode cur = head;
while (cur != null) {
int v = cur.val;
if (!cnt.containsKey(v))
cnt.put(v, 0);
cnt.put(v, cnt.get(v) + 1);
cur = cur.next;
}
ListNode start = new ListNode(-1);
ListNode end = start;
cur = head;
while (cur != null) {
int v = cur.val;
ListNode next =
cur.next; //记录下cur的下一个节点,不记录的话cur.next=null,就断开了
cur.next = null;
if (cnt.get(v) == 1) { //只保留出现一次的节点
end.next = cur;
end = end.next;
}
cur = next;
}
return start.next;
}
}