369 Plus One Linked List
Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
Example:
The Idea: A recursive solution to this is natural because we get a natural stack in the process. First iterate to the end. Then if the number is 9, then we know it must increment the next available base, so set it to 0. Otherwise if the number isn't 9, then we just increment the number and finish there with a flag. The final edge case to consider is when we finish iteration but no flag was triggered. This means value was zeroed out, and we must add a newListNode(1)
as the new head.
Complexity: O(N) time and space
Last updated