Remove Duplicates From an Unsorted Linked List
给一个链表, 删除里面所有重复的元素, 链表本身不是已排序的.
因为没有排序, 所以要用set查重. 然后新建个链表返回即可.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/** * 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 deleteDuplicatesUnsorted(ListNode head) { Map<Integer, Integer> count = new HashMap<>(); ListNode dummy = new ListNode(0); dummy.next = head; while(dummy.next != null) { count.put(dummy.next.val, count.getOrDefault(dummy.next.val, 0) + 1); dummy = dummy.next; } ListNode dn = new ListNode(0); ListNode res = dn; while(head != null) { if(count.get(head.val) <= 1){ dn.next = new ListNode(head.val); dn = dn.next; } head = head.next; } return res.next; } } |