Add Two Numbers II

Problem Id: 445 Difficulty: Medium


Intuition

Solution


class Solution:
    def _reverse(self, node):
        prev = None
        index = node
        while index:
            current = index
            index = index.next
            current.next = prev
            prev = current
        return prev

    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        l1 = self._reverse(l1)
        l2 = self._reverse(l2)
        head = ListNode(-1)
        index = head
        ex = 0
        while l1 or l2 or ex:
            tmp = ex
            if l1 is not None:
                tmp += l1.val
                l1 = l1.next
            if l2 is not None:
                tmp += l2.val
                l2 = l2.next
            ex = tmp // 10
            index.next = ListNode(tmp % 10)
            index = index.next
        return self._reverse(head.next)