Leetcode

82. Remove Duplicates from Sorted List II

Leeter 2021. 10. 23. 00:33

Description:

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

 

'''
[1] two pointers)

idea::
pointer write for linking next node, read1 and read2 for checking whether this node is duplicate or not

-T/C: O(n) # n==len(linked list)
-S/C: O(1)

'''

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy=ListNode(-1000,head)
        write=dummy
        read1=head
        
        while read1:
            count=0
            read2=read1
            
            while read2 and read1.val==read2.val:
                read2=read2.next
                count+=1
                
            if count==1:
                write=read1
                read1=read2
            
            else:
                write.next=read2
                read1=read2
                
        return dummy.next