
Sponsored
Sponsored
This approach involves iterating through both linked lists, node by node, adding corresponding values along with any carry from the previous addition. The result at each step is appended to a new linked list. If one list is longer than the other, the iteration continues on the longer list alone. A final check is done to handle any remaining carry.
Time Complexity: O(max(m, n)) where m and n are the lengths of the input lists. This is because we iterate through each node exactly once.
Space Complexity: O(max(m, n)) to store the resulting list.
1public class ListNode {
2 int val;
3 ListNode next;
4 ListNode(int val) { this.val = val; }
5}
6
7public class Solution {
8 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
9 ListNode dummy = new ListNode(0);
10 ListNode current = dummy;
11 int carry = 0;
12 while (l1 != null || l2 != null) {
13 int x = (l1 != null) ? l1.val : 0;
14 int y = (l2 != null) ? l2.val : 0;
15 int sum = carry + x + y;
16 carry = sum / 10;
17 current.next = new ListNode(sum % 10);
18 current = current.next;
19 if (l1 != null) l1 = l1.next;
20 if (l2 != null) l2 = l2.next;
21 }
22 if (carry > 0) {
23 current.next = new ListNode(carry);
24 }
25 return dummy.next;
26 }
27}The Java solution uses a dummy ListNode as a starting point, setting up carry handling similarly to the other languages, looping over the nodes of l1 and l2 and adjusting pointers.
The recursive approach solves the problem by recursing down the linked lists, accumulating values with carry and constructing the result linked list from the returned values from child calls. Each recursive call processes one pair of nodes from the lists, similar to how you would process each position in a sum independently in the iterative version.
Time Complexity: O(max(m, n))
Space Complexity: O(max(m, n)) because of the recursion stack.
1
In this C solution, we define a helper function addTwoNumbersRecursive that takes the two input lists and a carry. The function recursively creates new nodes based on the summed values ensuring that carry is also considered. The base case returns NULL when ends of both lists and no carry remain.