Add Two Numbers
You are given two non-negative integers, each stored as a singly linked list of single digits with the ones digit at the head — the digits are in reverse order, so 342 is stored as 2 → 4 → 3. Return their sum in the same form: a new linked list of digits, ones-first. The two lists may have different lengths, and the result may be longer than both (a final carry adds one more digit). Neither input has leading zeros, except the number 0 itself, which is the single node [0].
- The number of nodes in each list is in the range [1, 100]
- 0 <= Node.val <= 9
- No leading zeros except the number 0 itself.
l1 = [2,4,3], l2 = [5,6,4][7,0,8]l1 = [0], l2 = [0][0]l1 = [9,9,9,9], l2 = [9,9,9][8,9,9,0,1]Adding numbers in linked lists is actually easier when they are reversed because the "ones" place comes first. This mirrors exactly how we perform long addition on paper: start at the right, add digits, and carry the overflow to the left.
We use a Dummy Node to build our result list. In each step, we sum the values of the current nodes from both lists plus any carry from the previous step. The new digit is sum % 10, and the new carry is sum // 10.
dummy = Node(0)
curr = dummy
carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
# 1. Sum and Carry
val = v1 + v2 + carry
carry = val // 10
# 2. Append result
curr.next = Node(val % 10)
curr = curr.next
# 3. Step forward
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next