Problem
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.
Examples
Example 1:
|
|
Solution
Method 1 - Iterative with Reverse
To add one to a non-negative number represented as a singly linked list of digits, starting from the most significant digit:
- Reverse the Linked List: By reversing the list, we can easily add one to the number starting from the least significant digit, which is now the head of the reversed list.
- Add One: Traverse the reversed list, add one to the first node, and handle the carry if required.
- Reverse Again: Reverse the list again to restore the original order with the updated digits.
Here is the approach:
- Reverse the Linked List: Utilize a helper function to reverse the linked list.
- Add One:
- Traverse the reversed list and add one to the node’s value.
- Handle the carry: if a node becomes 10, set its value to 0 and carry the one to the next node.
- If the carry persists after the last node, append a new node with value 1.
- Reverse the Linked List Again to restore the original order.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of nodes in the linked list, as each step (reversing the list, adding one, and reversing the list again) takesO(n)
time. - 🧺 Space complexity:
O(1)
Method 2 - Recursive
A recursive approach can also be used to add one to a number represented as a singly linked list. By traversing the linked list to the very end and then adding one, we can handle the carry recursively while returning to the head of the list.
Here is the approach:
- Add a Fake Head: Create a dummy node before the actual head to handle cases where an additional digit is required (e.g., 999 + 1 = 1000).
- Recursive Carry Function: Define a recursive function that traverses to the end of the list.
- If the node is null, return a carry of 1.
- Recursively call the carry function for the next node.
- Add the carry to the current node’s value and update the node’s value.
- Return the carry obtained from the current addition.
- Return Result: After handling the carry, check if the dummy node’s value is non-zero. If so, return the dummy node; otherwise, return the original head.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the number of nodes, as each node is visited once. - 🧺 Space complexity:
O(n)
due to the recursive call stack.