Add Lists

Add Lists

Two non-negative numbers are stored as linked lists with their digits in reverse order (least-significant digit first). Add them and return the sum as a linked list in the same reversed-digit form.

addLists(a, b)

Input format: listA | listB, each a list of single digits (reversed). For example 2 4 3 represents 342.

Examples

(2 4 3) + (5 6 4)   // 342 + 465 = 807  → 7 0 8
(0) + (0)           // → 0
(9 9) + (1)         // 99 + 1 = 100      → 0 0 1

Walkthrough

Thinking it through

This is elementary-school column addition, represented as linked lists — and the reversed digit order isn't arbitrary, it's what makes this tractable. Adding by hand starts at the ones digit and works leftward, carrying when a column hits 10 or more. Storing the least-significant digit first means each list's head is exactly the digit to start from — no reversing needed.

Building the approach

  1. Walk both lists together from their heads.
  2. At each step, sum the current digit from A (0 if exhausted), the current digit from B (0 if exhausted), and the carry from the previous column.
  3. Record that sum mod 10; the new carry is the sum divided by 10, rounded down (0 or 1, since at most two digits plus a carry of 1).
  4. Advance whichever lists still have nodes.
  5. Keep going while either list has nodes left, or a carry remains — a carry off the last column needs its own new digit (99 + 1 = 100).

Why a dummy head helps here too

Appending computed digits onto a growing result list has the same "first node is special" problem as building any list from scratch. A dummy anchor node with a tracked tail pointer sidesteps it — the same technique used whenever a list is built incrementally.

Why this is the right approach

Since digits are stored least-significant-first, the list's natural head-to-tail order matches the natural addition order. A single synchronized walk carrying one small piece of state (the carry) is enough — no converting to numbers, no reversing, no lookahead. Each node is visited once; the result is proportional to the longer input (plus maybe one extra digit) — O(n) time and space.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.