The challenge
Add two nonnegative integers represented as reversed base-10 digit lists. Return a new reversed digit list.
Each value is a digit 0…9. Empty inputs represent zero. Inputs are not modified.
Example
[2, 4, 3] + [5, 6, 4] represents 342 + 465 → [7, 0, 8].
Use the walkthrough below to inspect the input and each state change.
See Add two numbers, step by step
Follow the pointers. Watch each link change.
A1headAA1headBB1Inspect node links
| Node | Value | Next |
|---|---|---|
| A1 | 2 | A2 |
| A2 | 4 | A3 |
| A3 | 3 | null |
| B1 | 5 | B2 |
| B2 | 6 | B3 |
| B3 | 4 | null |
Read the input
IDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links.
Start from the input head pointers.View original input
A: 2 (A1) → 4 (A2) → 3 (A3); B: 5 (B1) → 6 (B2) → 4 (B3); parameters: {}
Parameter indices are zero-based, except n from the end, which is one-based. Node IDs remain fixed when links change.
Put it into code
At each position, append sum modulo 10 and carry sum divided by 10.
Node stores val and next; the random-pointer lesson adds random. C++ uses C++17 or later.
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def add_numbers(a, b):
dummy = Node()
tail, carry = dummy, 0
while a or b or carry:
total = carry
if a:
total += a.val
a = a.next
if b:
total += b.val
b = b.next
carry, digit = divmod(total, 10)
tail.next = Node(digit)
tail = tail.next
return dummy.next if dummy.next else Node(0)
#include <cstddef>
struct Node {
int val;
Node* next;
Node(int value = 0, Node* link = nullptr)
: val(value), next(link) {}
};
Node* add_numbers(Node* a, Node* b) {
Node dummy;
Node* tail = &dummy;
int carry = 0;
while (a || b || carry) {
int total = carry;
if (a) { total += a->val; a = a->next; }
if (b) { total += b->val; b = b->next; }
carry = total / 10;
tail->next = new Node(total % 10);
tail = tail->next;
}
return dummy.next ? dummy.next : new Node(0);
}