Dummy head solution beats 87% of Python submissions

  • 0
    def removeElements(self, head, val):
        # Use dummy head.  This works because objects are pointers to heap memory locations.
        # p moves but dum stays pointed at original memory location.  
        node = head
        p = dum = ListNode(None)
        while node != None:
            if node.val == val:
                node = node.next
                p.next = None
                p.next = node
                node = node.next
                p = p.next
        return dum.next

Log in to reply

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