Related Articles
Multiply two numbers represented as linked lists into a third list
• Difficulty Level : Medium
• Last Updated : 30 Jul, 2020

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.
Examples:

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.
Algorithm

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

## Python3

Output:

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :