Python with two stacks.


  • 0
    J

    Putting the two list into stacks then calculate from the end.

        def addTwoNumbers(self, l1, l2):
            stack1 = []
            stack2 = []
    
            while l1 != None:
                stack1.append(l1)
                l1 = l1.next
            while l2 != None:
                stack2.append(l2)
                l2 = l2.next
            carry = 0
    
            longer = stack1 if len(stack1) > len(stack2) else stack2
            shorter = stack2 if len(stack1) > len(stack2) else stack1
    
            while len(shorter) != 0:
                lo = longer.pop()
                sh = shorter.pop()
    
                tempcarry = (lo.val+sh.val + carry) / 10
                lo.val = (lo.val+sh.val + carry) % 10
                carry = tempcarry
    
            if carry == 0:
                return lo if len(longer) == 0 else longer[0]
            else:
                while len(longer) != 0:
                    lo = longer.pop()
                    tempcarry = (lo.val+carry) /10
                    lo.val = (lo.val+carry) % 10
                    carry = tempcarry
    
                if carry == 0:
                    return lo if len(longer) == 0 else longer[0]
                else:
                    node = ListNode(carry)
                    node.next = lo
                    return node
    

Log in to reply
 

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