import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @return ListNode类 */ public ListNode deleteDuplicates (ListNode head) { // write code here if (head == null || head.next == null) { return head; } ListNode dummy = new ListNode(-1); ListNode tail = dummy; ListNode cur = head; while (cur != null) { int cnt = 0; int tmp = cur.val; ListNode pre = cur; while (cur != null && cur.val == tmp) { cnt++; cur = cur.next; } if (cnt == 1) { tail.next = pre; tail = pre; } } tail.next = null; return dummy.next; } public ListNode deleteDuplicates2 (ListNode head) { // write code here if (head == null || head.next == null) { return head; } Map<Integer, Integer> map = new HashMap<>(); ListNode cur = head; while (cur != null) { map.put(cur.val, map.getOrDefault(cur.val, 0) + 1); cur = cur.next; } ListNode dummy = new ListNode(-1); ListNode tail = dummy; cur = head; while (cur != null) { if (map.get(cur.val) == 1) { tail.next = cur; tail = cur; } cur = cur.next; } tail.next = null; return dummy.next; } }