Problem Statement
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Examples
-
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807
-
Input: l1 = [0], l2 = [0] Output: [0]
-
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]
Constraints
- The number of nodes in each linked list is in the range [1, 100]
- 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros
Solution
Here’s the implementation in C:
|
|
Algorithm Explanation
Step-by-Step Process
-
Initialize Variables:
carry
: Keeps track of the carry valueresultHead
: Points to the head of the result listtempNode
: Used to traverse and build the result list
-
Main Loop:
- Continue while either list has nodes or there’s a carry
- Add values from both lists and carry
- Calculate new digit and carry
- Create new node if needed
-
Handle Carry:
- If carry exists after processing all digits
- Create one more node with carry value
Key Points
-
Reverse Order:
- Numbers are stored in reverse order
- Makes addition simpler as we start from least significant digit
-
Carry Handling:
- Carry is calculated as sum/10
- New digit is calculated as sum%10
-
List Length:
- Solution handles lists of different lengths
- Continues until both lists are exhausted
Time and Space Complexity
-
Time Complexity: O(max(n,m))
- Where n and m are the lengths of the input lists
- We need to traverse the longer list
-
Space Complexity: O(max(n,m))
- We create a new list of length max(n,m) + 1
- Extra space for potential carry digit
Edge Cases
-
Different Length Lists:
- Solution handles lists of different lengths
- Continues processing until both lists are exhausted
-
Carry at End:
- Handles case where final sum produces a carry
- Creates additional node for carry value
-
Zero Values:
- Correctly handles lists with single zero value
- Maintains proper list structure
Testing
Here’s a test function to verify the solution:
|
|
Common Pitfalls
-
Memory Management:
- Always allocate memory for new nodes
- Consider memory leaks in production code
-
Carry Handling:
- Don’t forget to handle final carry
- Properly propagate carry through all digits
-
List Traversal:
- Check for NULL pointers
- Handle lists of different lengths
Conclusion
This solution efficiently adds two numbers represented by linked lists. The reverse order storage makes the addition process straightforward, while proper handling of carry and different list lengths ensures correct results for all test cases.
CPP version
|
|