
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 public int val;
3 public ListNode next;
4 public ListNode(int val=0, ListNode next=null) {
5 this.val = val;
6 this.next = next;
7 }
8}
9
10public class Solution {
11 public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
12 ListNode dummy = new ListNode(0);
13 ListNode current = dummy;
14 int carry = 0;
15 while (l1 != null || l2 != null) {
16 int x = (l1 != null) ? l1.val : 0;
17 int y = (l2 != null) ? l2.val : 0;
18 int sum = carry + x + y;
19 carry = sum / 10;
20 current.next = new ListNode(sum % 10);
21 current = current.next;
22 if (l1 != null) l1 = l1.next;
23 if (l2 != null) l2 = l2.next;
24 }
25 if (carry > 0) {
26 current.next = new ListNode(carry);
27 }
28 return dummy.next;
29 }
30}C# uses similar logic to ensure that carry and nodes are handled properly. Initialized a dummy ListNode to help with linking and cycle through nodes while adding corresponding values with carry management.
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.