解题思路
map记录数字出现的次数,出现次数大于1的数字从链表中移除
代码
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {ListNode dumpy = new ListNode(-1);dumpy.next=head;ListNode pre=dumpy;ListNode t=head;HashMap<Integer, Integer> integerIntegerHashMap = new HashMap<>();while (t!=null){integerIntegerHashMap.put(t.val,integerIntegerHashMap.getOrDefault(t.val,0)+1); t=t.next;} while (head!=null){if(integerIntegerHashMap.get(head.val)>1){pre.next=head.next;head=pre.next;}else {pre=head;head=head.next;}}return dumpy.next;}
}