LeetCode: 2. Add Two Numbers
Summary
Add two numbers represented by linked lists and build a new linked list for the result.
Approach
Pick nodes from the heads of both linked lists. Calculate the current digit and the carry for the next digit. Continue until both nodes are null.
Function
Initialization:
carry= 0l1,l2(current nodes)new_num = ListNode(0)tail = new_num
Main loop:
Use a while loop while either l1 or l2 is not null.
- Pick the nodes from
l1andl2. - Get values from the nodes. If a node is null, use zero.
- Add
l1.val + l2.val + carry = total. - Calculate
digit = total % 10andcarry = total // 10. - Append the new node to
new_num. - Move to the next nodes (
l1 = l1.next,l2 = l2.next) when available.
Complexity
Time Complexity: O(max(L1, L2)), where L1 is the length of l1 and L2 is the length of l2.
Space Complexity: O(1) auxiliary space.
Approach2
Recursive approach.
Function
Skipped, because it is almost the same.
Complexity
Time & Space Complexity: O(max(L1, L2))
The space complexity is worse than Approach 1.