Add 1 to Linked List
MediumP2Coding
A non-negative integer is stored in a singly linked list, one decimal digit per node, with the most significant digit at the head. Add one to the number and return the head of the resulting list. A list node has val and next. The ListNode class is already defined for you.
The list has no leading zeros except for the single digit 0 itself.
Example 1
- Input
- head = [1,2,3]
- Output
- [1,2,4]
Example 2
- Input
- head = [1,9,9]
- Output
- [2,0,0]
Example 3
- Input
- head = [9,9]
- Output
- [1,0,0]
Constraints
- 1 <= number of nodes <= 10^5
- 0 <= Node.val <= 9
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.