Increment a Number Stored as a Linked List
Implement addOne
Given the
head of a singly linked list where each node holds one digit of a non-negative number — most significant digit first — add 1 to the number and return the head of the resulting list.
This looks like ordinary addition, but a linked list can only walk forward, while carrying a +1 naturally flows from the last digit toward the first. The optimal solution resolves that mismatch with a reversal trickReverse, Operate, Reverse BackA common pattern for list problems where the natural order of operation runs opposite to the list's natural direction of traversal: reverse the list so the operation becomes a simple forward pass, do the work, then reverse back to restore the original order — all in O(1) extra space. — reverse the list so the least significant digit comes first, add with a simple forward-carrying pass, then reverse back.
Example 1:
Input: head = [1,2,9]
Output: [1,3,0]
Example 2:
Input: head = [9,9,9]
Output: [1,0,0,0]
Example 3:
Input: head = [0]
Output: [1]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ number of nodes in head ≤ 100 - ●
0 ≤ node value ≤ 9 - ●
The digits form a number with no leading zeros, except when the number itself is 0
head =
[1, 2, 9]