Given a linked list representing a non-negative integer, we are required to double this integer and convert it back to a linked list.
Intuition
We can just simulate the process, that is:
- Retrieve the integer represented by the linked list
- Double the integer
- Construct the result linked list from the result integer.
Approach
We can just simulate the process as above. However, if the integer is very large, retrieve the integer may cause overflow. To simplify this process, we can use a stack to store the digits of the original integer, then we double the integer by operating on the top of the stack.
In each step, we pop an element from the stack, doubling it and adding it with the carry digit. Then we construct the result linked list with inserting the new node in the front of the head.
Complexity
Time complexity: iterate all digits twice. $$O(n)$$
Space complexity: store the result linked list. $$O(n)$$
Code
|
|