← DiffPush

Add 1 to LL

Standard Bar Linked List · Medium Problems of LL O(N) · O(1)

Incrementing the Odometer Stored as a Chain

A legacy odometer stores its reading as a one-way chain of digits, most significant first — but incrementing must act on the least significant digit, which sits at the far end with no shortcut to it. The crew reverses the chain, runs the increment with a carry, appends a digit if the carry overflows the last node, and reverses back for display.

Input: An array head of node values, each a single digit 0-9, forming a non-negative integer with no leading zeros (except the number 0 itself).

Output: The digits of the number after adding 1, most significant first.

Constraints

Examples

Example 1

Input: {"head":[1,5,9]}
Output: [1,6,0]
159 + 1 = 160: the last digit rolls over and the carry dies at the tens place.

Example 2

Input: {"head":[9,9,9]}
Output: [1,0,0,0]
999 + 1 = 1000 — the carry survives every node, forcing a new leading digit.

Solve this in your browser →

Also on LeetCode ↗