解題思路
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;}
}