Given two numbers represented by linked lists, write a function that returns the head of the new linked list that represents the number that is the product of those numbers.
Input : 9->4->6 8->4 Output : 7->9->4->6->4 Input : 9->9->9->4->6->9 9->9->8->4->9 Output : 9->9->7->9->5->9->8->0->1->8->1
We have already discussed a solution in below post.
Multiply two numbers represented by Linked Lists
The solution discussed above store result in an integer. Her we store result in a third list so that large numbers can be handled.
Remember old school multiplication? we imitate that process. On paper, we take the last digit of a number and multiply with the second number and write the product. Now leave the last column and same way each digit of one number is multiplied with every digit of other number and every time result is written by leaving one last column. then add these columns that forms the number. Now assume these columns as nodes of the resultant linked list. We make resultant linked list in reversed fashion.
Reverse both linked lists Make a linked list of maximum result size (m + n + 1) For each node of one list For each node of second list a) Multiply nodes b) Add digit in result LL at corresponding position c) Now resultant node itself can be higher than one digit d) Make carry for next node Leave one last column means next time start From next node in result list Reverse the resulted linked list
First List is: 9->9->9->4->6->9 Second List is: 9->9->8->4->9 Resultant list is: 9->9->7->9->5->9->8->0->1->8->1
Note: we can take care of resultant node that can have more than 1 digit outside the loop just traverse the result list and add carry to next digit before reversing.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.