Python Program To Multiply Two Numbers Represented By Linked Lists
Last Updated :
31 Jul, 2023
Given two numbers represented by linked lists, write a function that returns the multiplication of these two linked lists.
Examples:
Input: 9->4->6
8->4
Output: 79464
Input: 3->2->1
1->2
Output: 3852
Python Program To Multiply Two Numbers Represented By Linked Lists
Traverse both lists and generate the required numbers to be multiplied and then return the multiplied values of the two numbers.
Algorithm to generate the number from linked list representation:
1) Initialize a variable to zero
2) Start traversing the linked list
3) Add the value of the first node to this variable
4) From the second node, multiply the variable by 10
and also take the modulus of this value by 10^9+7
and then add the value of the node to this
variable.
5) Repeat step 4 until we reach the last node of the list.
Use the above algorithm with both linked lists to generate the numbers.
Below is the program for multiplying two numbers represented as linked lists:
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
def printList( self ):
ptr = self .head
while (ptr ! = None ):
print (ptr.data,
end = '')
if ptr. next ! = None :
print ( '->' ,
end = '')
ptr = ptr. next
print ()
def multiplyTwoLists(first, second):
num1 = 0
num2 = 0
first_ptr = first.head
second_ptr = second.head
while first_ptr ! = None or second_ptr ! = None :
if first_ptr ! = None :
num1 = (num1 * 10 ) + first_ptr.data
first_ptr = first_ptr. next
if second_ptr ! = None :
num2 = (num2 * 10 ) + second_ptr.data
second_ptr = second_ptr. next
return num1 * num2
if __name__ = = '__main__' :
first = LinkedList()
second = LinkedList()
first.push( 6 )
first.push( 4 )
first.push( 9 )
print ( "First list is: " , end = '')
first.printList()
second.push( 4 )
second.push( 8 )
print ( "Second List is: " ,
end = '')
second.printList()
result = multiplyTwoLists(first,
second)
print ( "Result is: " , result)
|
Output:
First List is: 9->4->6
Second List is: 8->4
Result is: 79464
Time Complexity: O(max(n1, n2)), where n1 and n2 represents the number of nodes present in the first and second linked list respectively.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Please refer complete article on Multiply two numbers represented by Linked Lists for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...