Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program For Adding 1 To A Number Represented As Linked List
Next article icon

Python Program To Multiply Two Numbers Represented By Linked Lists

Last Updated : 31 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.

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
# Python3 to multiply two numbers # represented as Linked Lists    # Linked list node class  class Node:             # Function to initialize the node       def __init__(self, data):                 self.data = data          self.next = None         # Linked List Class class LinkedList:        # Function to initialize the     # LinkedList class.     def __init__(self):            # Initialize head as None         self.head = None        # Function to insert a node at the     # beginning of the Linked List     def push(self, new_data):                 # Create a new Node          new_node = Node(new_data)             # Make next of the new Node          # as head          new_node.next = self.head             # Move the head to point to          # new Node          self.head = new_node                # Function to print the Linked      # List     def printList(self):                 ptr = self.head           while (ptr != None):             print(ptr.data,                    end = '')             if ptr.next != None:                 print('->',                        end = '')                             ptr = ptr.next                        print()    # Multiply contents of two Linked  # Lists 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    # Driver code if __name__=='__main__':        first = LinkedList()     second = LinkedList()        # Create first Linked List 9->4->6     first.push(6)     first.push(4)     first.push(9)      # Printing first Linked List     print("First list is: ", end = '')     first.printList()        # Create second Linked List 8->4     second.push(4)     second.push(8)      # Printing second Linked List     print("Second List is: ",             end = '')     second.printList()        # Multiply two linked list and     # print the result     result = multiplyTwoLists(first,                                second)     print("Result is: ", result) # This code is contributed by kirtishsurangalikar 

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!


Next Article
Python Program For Adding 1 To A Number Represented As Linked List
author
kartik
Improve
Article Tags :
  • Linked List
  • Python Programs
  • DSA
  • Amazon
  • Modular Arithmetic
Practice Tags :
  • Amazon
  • Linked List
  • Modular Arithmetic

Similar Reads

  • Python Program To Add Two Numbers Represented By Linked Lists- Set 1
    Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers. Example: Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // re
    4 min read
  • Python Program To Subtract Two Numbers Represented As Linked Lists
    Given two linked lists that represent two large positive numbers. Subtract the smaller number from the larger one and return the difference as a linked list. Note that the input lists may be in any order, but we always need to subtract smaller from the larger ones.It may be assumed that there are no
    5 min read
  • Python Program to Multiply Two Binary Numbers
    Given two binary numbers, and the task is to write a Python program to multiply both numbers. Example: firstnumber = 110 secondnumber = 10 Multiplication Result = 1100 We can multiply two binary numbers in two ways using python, and these are: Using bin() functions andWithout using pre-defined funct
    2 min read
  • Python Program For Adding 1 To A Number Represented As Linked List
    Number is represented in linked list such that each digit corresponds to a node in linked list. Add 1 to it. For example 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0) Recommended: Please solve it on "PRACTICE" first, before moving on to
    4 min read
  • Python Program To Merge Two Sorted Lists (In-Place)
    Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: Input: head1: 5->7->9 head2: 4->6->8 Output: 4->5->6->7->8->9 Explanation: The output list is in sorted order. Input: head1: 1->3->5->7 head2: 2->4 Output: 1->2->3->4->5->7 Explanation: T
    5 min read
  • Python3 Program to Rotate Doubly linked list by N nodes
    Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list.   N = 2Rotated List:   Examples:   Input : a b c d e N = 2Output : c d e a b Input : a b c d e f g h N = 4Output : e f g h a b c
    4 min read
  • Python Program to Find LCM of Two Numbers
    We are given two numbers and our task is to find the LCM of two numbers in Python. In this article, we'll discuss different approaches to finding the LCM of two numbers in Python. Example: Input: a = 12, b = 15Output: 60Explanation: LCM of 12 and 15 is 60Python Program to Find LCM of Two NumbersBelo
    3 min read
  • Python Program to Find the Gcd of Two Numbers
    The task of finding the GCD (Greatest Common Divisor) of two numbers in Python involves determining the largest number that divides both input values without leaving a remainder. For example, if a = 60 and b = 48, the GCD is 12, as 12 is the largest number that divides both 60 and 48 evenly. Using e
    2 min read
  • Python Program to Multiply Two Matrices
    Given two matrices, we will have to create a program to multiply two matrices in Python. Example: Python Matrix Multiplication of Two-Dimension [GFGTABS] Python matrix_a = [[1, 2], [3, 4]] matrix_b = [[5, 6], [7, 8]] result = [[0, 0], [0, 0]] for i in range(2): for j in range(2): result[i][j] = (mat
    5 min read
  • Python Program For Merge Sort For Doubly Linked List
    Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences