Python version using a dummy head node - O(n)


  • 0
    G
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param head, a ListNode
        # @return a ListNode
        # 6:57
        def deleteDuplicates(self, head):
            dummyHead = ListNode(0)
            dummyHead.next = head
            
            last = dummyHead
    
            while last and last.next:
                if last.next and last.next.next and last.next.val == last.next.next.val:
                    self.removeDuplicate(last)
                else:
                    last = last.next
    
            return dummyHead.next
    
        def removeDuplicate(self, last):
            start = last.next
            end = last.next.next
            
            while end.next:
                if end.next.val == start.val:
                    end = end.next
                else:
                    break
            
            last.next = end.next

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.