2. Add Two Numbers

MediumLinked ListMathSimulationTimeO(max(m, n))SpaceO(max(m, n))
l1
2
4
3
l2
5
6
4
carry: 0
2 + 5 + 0 = ?
answer
digit 0: carry in = 0loop
Frame 1 / 13
1class Solution:
2 def addTwoNumbers(self, l1, l2):
3 head = current = None
4 carry = 0
5 while l1 or l2 or carry:
6 val1 = l1.val if l1 else 0
7 val2 = l2.val if l2 else 0
8 total = val1 + val2 + carry
9 carry = total // 10
10 digit = total % 10
11 node = ListNode(digit)
12 if head is None:
13 head = current = node
14 else:
15 current.next = node
16 current = current.next
17 l1 = l1.next if l1 else None
18 l2 = l2.next if l2 else None
19 return head