Add Two Numbers

Add two numbers represented as linked lists

Read Here
Step0 / 18
PhaseInitialize L1
L1 Length3
L2 Length3
Back To Linked List

Code

1def addTwoNumbers(l1, l2):
2 dummy = ListNode(0)
3 current = dummy
4 carry = 0
5
6 while l1 is not None or l2 is not None:
7 val1 = l1.val if l1 is not None else 0
8 val2 = l2.val if l2 is not None else 0
9
10 total = val1 + val2 + carry
11 carry = total // 10
12 digit = total % 10
13
14 current.next = ListNode(digit)
15 current = current.next
16
17 if l1 is not None:
18 l1 = l1.next
19 if l2 is not None:
20 l2 = l2.next
21
22 if carry > 0:
23 current.next = ListNode(carry)
24
25 return dummy.next
Create dummy head

Linked Lists

INIT L1

Step

0 / 18

Phase

Initialize L1

Carry

0

List 1

null2next4next3nextcurr

List 2

null5next6next4nextcurr

Result

null

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.