Simple Python Solution using Stack


  • 0
    M
    class Solution(object):
        def reverse(self, head):
            prev = None
            curr = head
            next = head.next
            while next:
                curr.next = prev
                prev = curr
                curr = next
                next = next.next
            curr.next = prev
            return curr
        
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            s1,s2 = [],[]
            while l1:
                s1.append(l1.val)
                l1 = l1.next
            while l2:
                s2.append(l2.val)
                l2 = l2.next
            
            d = ListNode(0)
            curr = d
            c = 0
            while s1 or s2:
                a = s1.pop() if s1 else 0
                b = s2.pop() if s2 else 0
                s = a + b + c
                c = s / 10
                curr.next = ListNode(s % 10)
                curr = curr.next
            if c > 0:
                curr.next = ListNode(c)
            return self.reverse(d.next)
            
    

Log in to reply
 

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