Open In App
Related Articles

Java Program To Multiply Two Numbers Represented By Linked Lists

Like Article
Save Article
Report issue

Given two numbers represented by linked lists, write a function that returns the multiplication of these two linked lists.


Input: 9->4->6
Output: 79464

Input: 3->2->1
Output: 3852

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


// Java program to Multiply two numbers
// represented as linked lists
import java.util.*;
public class GFG{
// Linked list node
static class Node
    int data;
    Node next;
    Node(int 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 =;
        if(second != null)
            num2 = (((num2) * 10) % N +
            second =;
    return (((num1 % N) *
             (num2 % N)) % N);
// A utility function to print a
// linked list
static void printList(Node node)
    while(node != null)
        if( != null)
        node =;
// Driver code
public static void main(String args[])
    // Create first list 9->4->6
    Node first = new Node(9); = new Node(4); = new Node(6);
    System.out.print("First List is: ");
    // Create second list 8->4
    Node second = new Node(8); = new Node(4);
    System.out.print("Second List is: ");
    // Multiply the two lists and see result
    System.out.print("Result is: ");
    System.out.println(multiplyTwoLists(first, second));
// This code is contributed by adityapande88



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!

Last Updated : 15 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Similar Reads