Add Two Numbers
Algorithm/LinkedList
Intuition
This problem involves adding two non-negative integers, where each integer is represented as a linked list with digits stored in reverse order. The challenge is to simulate elementary addition digit by digit, while managing carry-over. Since the lists are in reverse order, the least significant digit comes first, making it easier to add corresponding digits from both lists as we traverse them.
Approach
Below is the step-by-step breakdown of the approach:
- Initialize Variables:
- Use a dummy head node to simplify code and avoid edge case handling.
- Initialize a
current
pointer to track the current position in the result list. - Initialize a
carry
variable to manage carry-over from previous additions.
- Traverse the Lists:
- Use a while loop to iterate through both lists until both
l1
andl2
are exhausted. - At each step:
- Calculate the sum of the current digits from
l1
andl2
(or 0 if a list is exhausted), plus thecarry
. - Create a new node with the value
sum % 10
and attach it to the result list. - Update
carry
toMath.floor(sum / 10)
for the next iteration. - Move
current
,l1
, andl2
to their respective next nodes.
- Calculate the sum of the current digits from
- Use a while loop to iterate through both lists until both
- Handle Remaining Carry:
- After the loop, if any
carry
remains, add a new node with its value to the result list.
- After the loop, if any
- Return the Result:
- Return the next node of the dummy head, which is the head of the resultant linked list.
Complexity
- Time complexity: , we traverse both linked lists once, where
m
andn
are the lengths of the two lists. - Space complexity: , the result list can have at most one extra node beyond the longer of the two input lists to store the carry.