Python beats 99%, using O(1) space

  • 0

    Idea is use list1 as your output list, change node on list1 directly

    def addTwoNumbers(self, l1, l2):
            dummy = ListNode(0)
   = l1
            carry = 0
            prev = dummy
            while not(l1 is None and l2 is None):
                if l1 is None: #in case l1 is the shorter one
           = l2
                    tmp = l2
                    l2 = l1
                    l1 = tmp
                v1 = l1.val
                v2 = 0
                if l2 is not None:
                    v2 = l2.val
                s = v1 +v2 +carry
                digit = s%10
                carry = s/10
                l1.val = digit
                prev =
                l1 =
                if l2 is not None:
                    l2 =
            if carry!=0:

Log in to reply

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