
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.
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class Solution:
7 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
8 dummy = ListNode()
9 current = dummy
10 carry = 0
11 while l1 or l2:
12 x = l1.val if l1 else 0
13 y = l2.val if l2 else 0
14 sum = carry + x + y
15 carry = sum // 10
16 current.next = ListNode(sum % 10)
17 current = current.next
18 if l1: l1 = l1.next
19 if l2: l2 = l2.next
20 if carry > 0:
21 current.next = ListNode(carry)
22 return dummy.nextPython uses an iterative approach with a dummy head to simplify list handling. Carries are calculated and updated with each node of the result as lists are traversed until finished.
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.