Add Two Numbers
Add two numbers represented as linked lists
Code
1def addTwoNumbers(l1, l2):2 dummy = ListNode(0)3 current = dummy4 carry = 056 while l1 is not None or l2 is not None:7 val1 = l1.val if l1 is not None else 08 val2 = l2.val if l2 is not None else 0910 total = val1 + val2 + carry11 carry = total // 1012 digit = total % 101314 current.next = ListNode(digit)15 current = current.next1617 if l1 is not None:18 l1 = l1.next19 if l2 is not None:20 l2 = l2.next2122 if carry > 0:23 current.next = ListNode(carry)2425 return dummy.next
Create dummy head
Linked Lists
INIT L1
Step
0 / 18
Phase
Initialize L1
Carry
0
List 1
List 2
Result
Progress
Processing
Result So Far
[Empty]
Pointer State
Pointers
l1
2
l2
5
current
null
carry
0
Key Insight
Carry propagates to the next digit. If carry remains after processing all nodes, add it as a final node.
Explanation
Init
Initialize Pointers
Set up pointers for both input lists and the result list.
💡 Tip
We'll traverse both lists simultaneously.