Problem Description
Given two non-empty linked lists representing two non-negative integers with their most significant digit coming first, compute their sum and return it as a linked list. Each node contains a single digit, and the numbers do not have any extra leading zeros. The challenge is to complete this task without reversing the input lists (i.e., by using an alternative approach).
Key Insights
- Use stacks to simulate processing the digits from least significant (end of the list) to most significant (start of the list).
- By pushing each list’s values onto a stack, you can pop them off in reverse order and perform addition with a carry.
- Create new nodes for the resulting linked list as you compute the sum, linking them appropriately in reverse order.
- Careful handling of the carry value is critical for correct summation.
Space and Time Complexity
Time Complexity: O(n + m) where n and m are the lengths of the two linked lists. Space Complexity: O(n + m) due to the use of stacks to hold the nodes' values and the space needed for the result list.
Solution
We begin by pushing the values of each linked list onto two separate stacks, which allows us to retrieve the digits in reverse order for addition. Then we pop elements from both stacks, add them along with any carry from the previous addition, and create a new node for each digit of the resultant sum. Finally, the new nodes are prepended to the resultant list. This approach avoids modifying the input lists (i.e., no reversal is performed on the original linked lists) and handles different list lengths and carry propagation gracefully.