Multiply two numbers represented by Linked Lists

22 Jun, 2022
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
Solution: 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 first node to this variable
4) From the second node, multiply the variable by 10
   and also take 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 of linked lists to generate the numbers. 
Below is the program for multiplying two numbers represented as linked lists:  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
C
Java
Python3
C#
Javascript
// C++ program to Multiply two numbers// represented as linked lists#include<bits/stdc++.h>#include<stdio.h>using namespace std;    // Linked list nodestruct Node{    int data;    struct Node* next;};    // Function to create a new node // with given datastruct Node *newNode(int data){    struct Node *new_node = (struct Node *) malloc(sizeof(struct Node));    new_node->data = data;    new_node->next = NULL;    return new_node;}    // Function to insert a node at the // beginning of the Linked Listvoid push(struct Node** head_ref, int new_data){    // allocate node     struct Node* new_node = newNode(new_data);        // link the old list off the new node     new_node->next = (*head_ref);        // move the head to point to the new node     (*head_ref) = new_node;}    // Multiply contents of two linked listslong long multiplyTwoLists (Node* first, Node* second){    long long N= 1000000007;    long long num1 = 0, num2 = 0;    while (first || second){                  if(first){            num1 = ((num1)*10)%N + first->data;            first = first->next;        }                  if(second)        {            num2 = ((num2)*10)%N + second->data;            second = second->next;        }              }    return ((num1%N)*(num2%N))%N;}    // A utility function to print a linked listvoid printList(struct Node *node){    while(node != NULL)    {        cout<<node->data;        if(node->next)            cout<<"->";        node = node->next;    }    cout<<"\n";}    // Driver program to test above functionint main(){    struct Node* first = NULL;    struct Node* second = NULL;        // create first list 9->4->6    push(&first, 6);    push(&first, 4);    push(&first, 9);    printf("First List is: ");    printList(first);        // create second list 8->4    push(&second, 4);    push(&second, 8);    printf("Second List is: ");    printList(second);        // Multiply the two lists and see result    cout<<"Result is: ";    cout<<multiplyTwoLists(first, second);        return 0;}  // This code is contributed by Sania Kumari Gupta (kriSania804)
// C program to Multiply two numbers// represented as linked lists#include <stdio.h>#include <stdlib.h>// Linked list nodetypedef struct Node {    int data;    struct Node* next;} Node;  // Function to create a new node// with given datastruct Node* newNode(int data){    Node* new_node = (Node*)malloc(sizeof(Node));    new_node->data = data;    new_node->next = NULL;    return new_node;}  // Function to insert a node at the// beginning of the Linked Listvoid push(struct Node** head_ref, int new_data){    // allocate node    struct Node* new_node = newNode(new_data);      // link the old list off the new node    new_node->next = (*head_ref);      // move the head to point to the new node    (*head_ref) = new_node;}  // Multiply contents of two linked listslong long multiplyTwoLists(Node* first, Node* second){    long long N = 1000000007;    long long num1 = 0, num2 = 0;    while (first || second) {          if (first) {            num1 = ((num1)*10) % N + first->data;            first = first->next;        }          if (second) {            num2 = ((num2)*10) % N + second->data;            second = second->next;        }    }    return ((num1 % N) * (num2 % N)) % N;}  // A utility function to print a linked listvoid printList(struct Node* node){    while (node != NULL) {        printf("%d", node->data);        if (node->next)            printf("->");        node = node->next;    }    printf("\n");}  // Driver program to test above functionint main(){    struct Node* first = NULL;    struct Node* second = NULL;      // create first list 9->4->6    push(&first, 6);    push(&first, 4);    push(&first, 9);    printf("First List is: ");    printList(first);      // create second list 8->4    push(&second, 4);    push(&second, 8);    printf("Second List is: ");    printList(second);      // Multiply the two lists and see result    printf("Result is: ");    printf("%lld", multiplyTwoLists(first, second));      return 0;}  // This code is contributed by Sania Kumari Gupta// (kriSania804)
// Java program to Multiply two numbers// represented as linked listsimport java.util.*;  public class GFG{      // Linked list node    static class Node    {        int data;        Node next;                  Node(int data){            this.data = data;            next = null;        }    }      // Multiply contents of two linked lists    static long multiplyTwoLists(Node first, Node second)    {        long N = 1000000007;        long num1 = 0, num2 = 0;          while (first != null || second !=  null){                          if(first != null){                num1 = ((num1)*10)%N + first.data;                first = first.next;            }                          if(second != null)            {                num2 = ((num2)*10)%N + second.data;                second = second.next;            }                      }        return ((num1%N)*(num2%N))%N;    }      // A utility function to print a linked list    static void printList(Node node)    {        while(node != null)        {            System.out.print(node.data);            if(node.next != null)                System.out.print("->");            node = node.next;        }        System.out.println();    }      // Driver program to test above function    public static void main(String args[])    {        // create first list 9->4->6        Node first = new Node(9);        first.next = new Node(4);        first.next.next = new Node(6);        System.out.print("First List is: ");        printList(first);          // create second list 8->4        Node second = new Node(8);        second.next = new Node(4);        System.out.print("Second List is: ");        printList(second);          // Multiply the two lists and see result        System.out.print("Result is: ");        System.out.println(multiplyTwoLists(first, second));    }}  // This code is contributed by adityapande88
# 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 Classclass 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 Listsdef 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 codeif __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
// C++ program to Multiply two numbers// represented as linked listsusing System;public class GFG{        // Linked list node    public class Node {        public int data;        public Node next;        public Node(int data)        {            this.data = data;            this.next = null;        }    }    // Multiply contents of two linked lists    public static long multiplyTwoLists(Node first,                                        Node second)    {        var N = 1000000007;        var num1 = 0;        var num2 = 0;        while (first != null || second != null) {            if (first != null) {                num1 = ((num1)*10) % N + first.data;                first = first.next;            }            if (second != null) {                num2 = ((num2)*10) % N + second.data;                second = second.next;            }        }        return ((num1 % N) * (num2 % N)) % N;    }    // A utility function to print a linked list    public static void printList(Node node)    {        while (node != null) {            Console.Write(node.data);            if (node.next != null) {                Console.Write("->");            }            node = node.next;        }        Console.WriteLine();    }    // Driver program to test above function    public static void Main(String[] args)    {        // create first list 9->4->6        var first = new Node(9);        first.next = new Node(4);        first.next.next = new Node(6);        Console.Write("First List is: ");        GFG.printList(first);                // create second list 8->4        var second = new Node(8);        second.next = new Node(4);        Console.Write("Second List is: ");        GFG.printList(second);                // Multiply the two lists and see result        Console.Write("Result is: ");        Console.WriteLine(            GFG.multiplyTwoLists(first, second));    }}  // This code is contributed by mukulsomukesh
<script>// Javascript program to Multiply two numbers// represented as linked lists  // Linked list nodeclass Node{    constructor(data)    {        this.data=data;        this.next = null;    }}  // Multiply contents of two linked listsfunction multiplyTwoLists(first,second){     let N = 1000000007;        let num1 = 0, num2 = 0;           while (first != null || second !=  null){                           if(first != null){                num1 = ((num1)*10)%N + first.data;                first = first.next;            }                           if(second != null)            {                num2 = ((num2)*10)%N + second.data;                second = second.next;            }                       }        return ((num1%N)*(num2%N))%N;    }             // A utility function to print a linked list    function printList(node)    {        while(node != null)        {            document.write(node.data);            if(node.next != null)                document.write("->");            node = node.next;        }        document.write("<br>");    }          // Driver program to test above function// create first list 9->4->6let first = new Node(9);first.next = new Node(4);first.next.next = new Node(6);document.write("First List is: ");printList(first);  // create second list 8->4let second = new Node(8);second.next = new Node(4);document.write("Second List is: ");printList(second);  // Multiply the two lists and see resultdocument.write("Result is: ");document.write(multiplyTwoLists(first, second)+"<br>");  // This code is contributed by avanitrachhadiya2155</script>
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.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
harishkumar88
andrew1234
princiraj1992
daljeetsingh22sk9
adityapande88
kirtishsurangalikar
avanitrachhadiya2155
mukulsomukesh
krisania804
samim2000
Amazon
Modular Arithmetic
Linked List
Amazon
Linked List
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Linked List vs Array
Implementing a Linked List in Java using Class
Find Length of a Linked List (Iterative and Recursive)
Function to check if a singly linked list is palindrome
Queue - Linked List Implementation
Write a function to get the intersection point of two Linked Lists
Remove duplicates from an unsorted linked list