Skip to content

Add two numbers

Add two numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next: ListNode = next

    def print(self):
        print(self.val)
        if self.next:
            self.next.print()
def add_two_numbers(l1: ListNode, l2: ListNode, c = 0) -> ListNode:
    val = l1.val + l2.val + c
    c = val // 10
    ret = ListNode(val % 10)

    if l1.next or l2.next or c > 0:
        if not l1.next:
            l1.next = ListNode(0)

        if not l2.next:
            l2.next = ListNode(0)

        ret.next = add_two_numbers(l1.next, l2.next, c)
    return ret

Create list

node1 = ListNode(2)
node1.next = ListNode(4)
node1.next.next = ListNode(3)

node2 = ListNode(5)
node2.next = ListNode(6)
node2.next.next = ListNode(4)

print("Node 1")
node1.print()
print("Node 2")
node2.print()
Node 1
2
4
3
Node 2
5
6
4

Result

result = add_two_numbers(node1, node2)
result.print()
7
0
8

Time: \(O(n)\)