Plus One Linked List Problem
Description
LeetCode Problem 369.
Given a non-negative integer represented as a linked list of digits, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list.
Example 1:
Input: head = [1,2,3]
Output: [1,2,4]
Example 2:
Input: head = [0]
Output: [1]
Constraints:
- The number of nodes in the linked list is in the range
[1, 100]. 0 <= Node.val <= 9- The number represented by the linked list does not contain leading zeros except for the zero itself.
Solution
Approach: Find the Last Digit That Is Not 9
Adding one changes only the end of the number. The trailing 9s turn into 0s, and the digit just before them goes up by one. For example, 1 2 9 9 becomes 1 3 0 0. So we don't need to reverse the list or do any recursion. We only need to find the last node whose value is not 9.
Put a dummy node with value 0 in front of the head. It handles the case where every digit is 9, like 9 9 9, which needs a new leading digit. Walk the list and remember the last non-9 node, starting with the dummy. Then add one to that node and set every node after it to 0.
If the dummy node is now 1, the number gained a digit, and the dummy becomes the new head. Otherwise return the original head.
Complexity: O(n) time, two passes over the list at most. O(1) extra space.
class Solution:
def plusOne(self, head: Optional[ListNode]) -> Optional[ListNode]:
# a 0 in front of the number takes the carry if every digit is 9
dummy = ListNode(0, head)
# the last digit that is not 9: it goes up by one, and the 9s after it become 0
last = dummy
node = head
while node:
if node.val != 9:
last = node
node = node.next
last.val += 1
node = last.next
while node:
node.val = 0
node = node.next
return dummy if dummy.val else dummy.next