Two reversed-digit lists are already aligned for grade-school addition — walk both once, one column per step, and let a single carry bit remember everything.
Add one column at a time and let a single carry bit remember everything.
On paper you add from the ones column upward, but numerals are written most-significant-first — so you must start at the far end. Here LeetCode already flipped the lists: the head is the ones digit. That turns addition into a single left-to-right walk with one bit of memory.
Step through 342 + 465 digit by digit. Each frame writes exactly one result node and updates the carry chip — the only state the walk remembers.
class Solution:
def addTwoNumbers(self, l1, l2):
dummy = ListNode(0) # sentinel: never moves; dummy.next is the answer
cur, carry = dummy, 0
while l1 or l2 or carry: # carry in the test emits the final node
x = l1.val if l1 else 0 # a missing node reads as 0
y = l2.val if l2 else 0
s = x + y + carry
cur.next = ListNode(s % 10) # this column's digit
carry = s // 10 # 0 or 1: the only state kept
cur = cur.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next
The displayed Python and the trace above use the same boundary logic: missing node = 0, carry folded into the loop test.
x = l1.val if l1 else 0The short list contributes 0 once exhausted — no padding pass, no length precompute needed.carry = s // 10 ∈ {0, 1}Max column total is 9 + 9 + 1 = 19, so the carry is always a single bit. That is why O(1) extra state suffices.while l1 or l2 or carryPutting carry in the loop condition appends the final node (5 + 5 → [0, 1]) with no special-case code after the loop.342 + 465 = 807. The tens column 4 + 6 = 10 writes 0 and carries 1 into the hundreds — the carry chip lighting up is the moment to watch.
9,999,999 + 9,999 = 10,009,998. The carry ripples through four columns then dies — then the loop runs three more silent columns before both lists end.
Reversed order means the head is the ones digit, so I walk both lists once: each column writes one node with s mod 10 and forwards s over 10 as the carry. Missing nodes read as zero, and the carry in the loop condition emits the final node.