Remove Duplicates From an Unsorted Linked List

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def deleteDuplicatesUnsorted(self, head: ListNode) -> ListNode:
        # Dictionary to store the count of occurrences
        count_dict = {}
        current = head
        while current:
            count_dict[current.val] = count_dict.get(current.val, 0) + 1
            current = current.next

        # Dummy node to help with head handling
        dummy = ListNode(0)
        prev = dummy
        current = head
        while current:
            if count_dict[current.val] == 1: # Only keep nodes with a count of 1
                prev.next = current
                prev = current
            current = current.next
            prev.next = None # Ensure last node's next is None

        return dummy.next # Skip dummy node and return the actual head