Given two numbers represented by two lists, write a function that returns the sum list. The sum list is list representation of the addition of two input numbers.
List1: 5->6->3 // represents number 365
List2: 8->4->2 // represents number 248
Resultant list: 3->1->6 // represents number 613
Explanation: 365 + 248 = 613
List1: 7->5->9->4->6 // represents number 64957
List2: 8->4 // represents number 48
Resultant list: 5->0->0->5->6 // represents number 65005
Explanation: 64957 + 48 = 65005
Approach: Traverse both lists and One by one pick nodes of both lists and add the values. If the sum is more than 10 then make carry as 1 and reduce sum. If one list has more elements than the other then consider remaining values of this list as 0.
The steps are:
- Traverse the two linked lists from start to end
- Add the two digits each from respective linked lists.
- If one of the list has reached the end then take 0 as its digit.
- Continue it until both the lists end.
- If the sum of two digits is greater than 9 then set carry as and the current digit as sum % 10
Below is the implementation of this approach.
First List is 7 5 9 4 6 Second List is 8 4 Resultant list is 5 0 0 5 6
- Time Complexity: O(m + n), where m and n are number of nodes in first and second lists respectively.
The lists needs to be traversed only once.
- Space Complexity: O(m + n).
A temporary linked list is needed to store the output number.
Related Article: Add two numbers represented by linked lists | Set 2
Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Add Two Numbers Represented by Linked Lists | Set 3
- Add two numbers represented by linked lists | Set 2
- Multiply two numbers represented by Linked Lists
- Subtract Two Numbers represented as Linked Lists
- Compare numbers represented by 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 1 to a number represented as linked list
- Add one to a number represented as linked list | Set 2
- Reverse all the word in a String represented as a Linked List
- Multiply Large Numbers represented as Strings
- Identical Linked Lists
- Check if two Linked Lists are permutations of each other
- Union and Intersection of two Linked Lists
- First common element in two linked lists
- Intersection of two Sorted Linked Lists
- Merge Sort for Linked Lists
- Merge two sorted linked lists