Easy to understand, one time scan of list with extra O(1) space


  • 0
    L
    class Solution:
        # @param {ListNode} head
        # @return {ListNode}
        def deleteDuplicates(self, head):
            node = head
            prev = ListNode(0)
            prev.next = head
            head = prev
    
            while node:
                #Check if current node is a duplicated node
                flag = False
                while node.next and node.val == node.next.val:
                    node.next = node.next.next
                    flag = True
                #Node is now pointer of a list with each element appears only once
                node = node.next
                #Delete the current node if its value appeared more than once
                if flag and prev.next:
                    prev.next = prev.next.next
                #Put the node at the end of the result
                else:
                    prev = prev.next
    
            return head.next

Log in to reply
 

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