Given two numbers represented by two linked lists, write a function that returns the sum list. The sum list is linked list representation of the addition of two input numbers. It is not allowed to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion).
Input: First List: 5->6->3 // represents number 563 Second List: 8->4->2 // represents number 842 Output Resultant list: 1->4->0->5 // represents number 1405
We have discussed a solution here which is for linked lists where a least significant digit is the first node of lists and the most significant digit is the last node. In this problem, the most significant node is the first node and the least significant digit is the last node and we are not allowed to modify the lists. Recursion is used here to calculate sum from right to left.
Following are the steps.
1) Calculate sizes of given two linked lists.
2) If sizes are same, then calculate sum using recursion. Hold all nodes in recursion call stack till the rightmost node, calculate the sum of rightmost nodes and forward carry to the left side.
3) If size is not same, then follow below steps:
….a) Calculate difference of sizes of two linked lists. Let the difference be diff
….b) Move diff nodes ahead in the bigger linked list. Now use step 2 to calculate the sum of the smaller list and right sub-list (of the same size) of a larger list. Also, store the carry of this sum.
….c) Calculate the sum of the carry (calculated in the previous step) with the remaining left sub-list of a larger list. Nodes of this sum are added at the beginning of the sum list obtained the previous step.
Below is a dry run of the above approach:
Below image is the implementation of the above approach.
1 0 1 7
Time Complexity: O(m+n) where m and n are the sizes of given two linked lists.
Related Article : Add two numbers represented by linked lists | Set 1
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Add Two Numbers Represented by Linked Lists | Set 3
- Add two numbers represented by linked lists | Set 1
- Multiply two numbers represented by Linked Lists
- Subtract Two Numbers represented as Linked Lists
- Multiply two numbers represented as linked lists into a third list
- Compare two strings represented as linked lists
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Create a linked list from two linked lists by choosing max element at each position
- Add one to a number represented as linked list | Set 2
- Add 1 to a number represented as linked list
- Add two numbers represented by two arrays
- Sum of two numbers where one number is represented as array of digits
- Multiply Large Numbers represented as Strings
- Modulo power for large numbers represented as strings
- Identical Linked Lists
Improved By : rathbhupendra