Given two numbers represented by two linked lists, the task is to return the sum of these numbers in the form of a linked list.
Input: 9->2->7->null, 9->3->null
Output: 1->0->2->0->null
Input: 7->5->9->4->6->null, 8->4->null
Output: 8->4->null
Solutions
Method 1: Iterative
In this approach, we reverse these two lists and start from the head of the lists to add the numbers of individual nodes, just as we would in practise if we added two numbers.
Follow the steps below to solve the problem:
Reverse the two number lists.
Simulate addition at nodes one by one.
Append each node before the already calculated sum of nodes.
In the end, we will get the final answer and we can return the head node.
Complexity
The time complexity of this solution is O(max(n,m)) and space complexity is O(1).