The Wayback Machine - https://web.archive.org/web/20241007203407/https://www.geeksforgeeks.org/multiply-two-numbers-represented-linked-lists/
Open In App

Multiply two numbers represented by Linked Lists

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two numbers represented by linked lists, The task is to return the multiplication of these two linked lists.

Examples: 

Input : head1 : 1->0->0 , head2 : 1->0
Output: 1000
Explanation: head1 represents 100 and head2 represents the number 10, 100 x 10 = 1000

Input : head1 : 3->2, head2 : 2
Output: 64
Explanation: head1 represents 32 and head2 represents the number 2, 32 x 2= 64

Approach:

To multiply two numbers represented by linked lists, you need to traverse each linked list from the head node to the end. For each linked list, initialize a variable to zero, which will be used to store the numerical value of the linked list. By processing each node, start by adding the value of the first node to this variable. For each subsequent node, multiply the variable by 10 and then add the node’s value to it. This approach effectively reconstructs the number represented by the linked list. To handle potential overflow and ensure that the computations remain within manageable bounds, use the modulo operation with 1e9 + 7 after each arithmetic operation. This will keep the intermediate results within a safe range and prevent overflow during multiplication.

Below is the implementation of the above approach :

C++
// C++ program to Multiply two numbers 
// represented as linked lists
#include <iostream>
using namespace std;

long long MOD = 1000000007;

class Node {
public:
    int data;
    Node* next;
      Node(int x) {
         data = x;
          next = nullptr;
    }
};

// Multiply contents of two linked lists
long long multiplyTwoLists(Node* first, Node* second) {
    long long num1 = 0, num2 = 0;

    // Traverse the first list and 
      // construct the number with modulo
    while (first != nullptr) {
        num1 = (num1 * 10 + first->data) % MOD;
        first = first->next;
    }

    // Traverse the second list and 
      // construct the number with modulo
    while (second != nullptr) {
        num2 = (num2 * 10 + second->data) % MOD;
        second = second->next;
    }

    // Return the product of the 
      // two numbers with modulo
    return (num1 * num2) % MOD;
}

void printList(Node* curr) {
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
}

int main() {
  
    // Create first list 9->4->6
    Node* head1 = new Node(9);
    head1->next = new Node(4);
    head1->next->next = new Node(6);
  
    // Create second list 8->4
    Node* head2 = new Node(8);
      head2->next = new Node(4);
    cout << multiplyTwoLists(head1, head2) << endl;

    return 0;
}
C
// C program to Multiply two numbers
// represented as linked lists
#include <stdlib.h>
#define MOD 1000000007

struct Node {
    int data;
    struct Node *next;
};

// Multiply contents of two linked lists
long long multiplyTwoLists(struct Node *first, struct Node *second) {
    long long num1 = 0, num2 = 0;

    // Traverse the first list and
    // construct the number with modulo
    while (first != NULL) {
        num1 = (num1 * 10 + first->data) % MOD;
        first = first->next;
    }

    // Traverse the second list and
    // construct the number with modulo
    while (second != NULL) {
        num2 = (num2 * 10 + second->data) % MOD;
        second = second->next;
    }

    // Return the product of the two 
      // numbers with modulo
    return (num1 * num2) % MOD;
}

void printList(struct Node *curr) {
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
}

struct Node *createNode(int data) {
    struct Node *newNode = 
      (struct Node *)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

int main() {

    // Create first list 9->4->6
    struct Node *head1 = createNode(9);
    head1->next = createNode(4);
    head1->next->next = createNode(6);

    // Create second list 8->4
    struct Node *head2 = createNode(8);
    head2->next = createNode(4);
    printf("%lld\n", multiplyTwoLists(head1, head2));

    return 0;
}
Java
// Java program to Multiply two numbers
// represented as linked lists

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

public class GfG {
  
    // Multiply contents of two linked lists
    static long multiplyTwoLists(Node first, Node second) {
        long MOD = 1000000007;
        long num1 = 0, num2 = 0;
      
        // Traverse the first list and 
          // construct the number with modulo
        while (first != null || second != null) {
            if (first != null) {
                num1 = ((num1 * 10) + first.data) % MOD;
                first = first.next;
            }
          
            // Traverse the second list and 
              // construct the number with modulo
            if (second != null) {
                num2 = ((num2 * 10) + second.data) % MOD;
                second = second.next;
            }
        }
      
          // Return the product of the two 
          // numbers with modulo
        return (num1 * num2) % MOD;
    }
    static void printList(Node curr) {
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
    }

    public static void main(String args[]) {
      
        // create first list 9->4->6
        Node head1 = new Node(9);
        head1.next = new Node(4);
        head1.next.next = new Node(6);

        // create second list 8->4
        Node head2 = new Node(8);
        head2.next = new Node(4);
        System.out.println(multiplyTwoLists(head1, head2));
    }
}
Python
# Python3 to multiply two numbers
# represented as Linked Lists

MOD = 1000000007

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Multiply contents of two linked lists
def multiplyTwoLists(first, second):
    num1 = 0
    num2 = 0

    # Traverse the first list and 
    # construct the number with modulo
    while first is not None:
        num1 = (num1 * 10 + first.data) % MOD
        first = first.next

    # Traverse the second list and 
    # construct the number with modulo
    while second is not None:
        num2 = (num2 * 10 + second.data) % MOD
        second = second.next

    # Return the product of the two
    # numbers with modulo
    return (num1 * num2) % MOD

def printList(curr):
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next

if __name__ == "__main__":

    # Create first list 9->4->6
    head1 = Node(9)
    head1.next = Node(4)
    head1.next.next = Node(6)
    
    # Create second list 8->4
    head2 = Node(8)
    head2.next = Node(4)
    print(multiplyTwoLists(head1, head2))
C#
// C++ program to Multiply two numbers
// represented as linked lists

using System;
public class Node {
    public int data;
    public Node next;
    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}
class GfG {

    // Multiply contents of two linked lists
    static long multiply(Node first, Node second) {
        var MOD = 1000000007;
        var num1 = 0;
        var num2 = 0;

        // Traverse the first list and
        // construct the number with modulo
        while (first != null || second != null) {
            if (first != null) {
                num1 = ((num1)*10) % MOD + first.data;
                first = first.next;
            }
            if (second != null) {
                num2 = ((num2)*10) % MOD + second.data;
                second = second.next;
            }
        }

        // Return the product of the two 
          // numbers with modul
        return ((num1 % MOD) * (num2 % MOD)) % MOD;
    }

    static void printList(Node curr) {
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
    }
    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);
      
        // create second list 8->4
        var second = new Node(8);
        second.next = new Node(4);
        Console.WriteLine(multiply(first, second));
    }
}
JavaScript
// JavaScript program to Multiply two numbers
// represented as linked lists

const MOD = 1000000007;

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Multiply contents of two linked lists
function multiplyTwoLists(first, second) {
    let num1 = 0, num2 = 0;

    // Traverse the first list and 
    // construct the number with modulo
    while (first !== null) {
        num1 = (num1 * 10 + first.data) % MOD;
        first = first.next;
    }

    // Traverse the second list and 
    // construct the number with modulo
    while (second !== null) {
        num2 = (num2 * 10 + second.data) % MOD;
        second = second.next;
    }

    // Return the product of the two 
    // numbers with modulo
    return (num1 * num2) % MOD;
}

function printList(curr) {
    while (curr !== null) {
        console.log(curr.data + " ");
        curr = curr.next;
    }
    console.log();
}

// Create first list 9->4->6
let head1 = new Node(9);
head1.next = new Node(4);
head1.next.next = new Node(6);

// Create second list 8->4
let head2 = new Node(8);
head2.next = new Node(4);
console.log(multiplyTwoLists(head1, head2));

Output
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)



Similar Reads

Multiply two numbers represented as linked lists into a third list
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-
15+ min read
Javascript Program To Multiply Two Numbers Represented By Linked Lists
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->4Output: 79464Input: 3->2->1 1->2Output: 3852Solution: Traverse both lists and generate the required numbers to be multiplied and then return the multiplied values of the two number
2 min read
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 ones from larger ones.Note: It may be assumed that there are no extra leading zeros in input lists. Exampl
15+ min read
Javascript 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 extra leading zeros in input lists. Examples: Inp
5 min read
Javascript Program For Adding Two Numbers Represented By Linked Lists- Set 2
Given two numbers represented by two linked lists, write a function that returns the sum list. The sum list is linked list representation of the addition of two input numbers. It is not allowed to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion). Example : Input:First List: 5->6->3 Second List: 8->4-
8 min read
Javascript 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 // represents number 1405 Explanat
4 min read
Multiply a single digit number in place to a number represented as a Linked List
Given a linked list of N nodes where each node represents digits of a number and a single-digit number M, the task is to multiply the list by M in-place and print the resulting linked list. Examples: Input: Linked list: 1 ? 2 ? 7 ? 3 ? NULL, M = 3Output: 3 ? 8 ? 1 ? 9 ? NULLExplanation: The given linked list represents the number 1273. Multiplying
12 min read
Compare numbers represented by Linked Lists
Given the pointers to the head nodes of two linked lists. The task is to compare the numbers represented by the linked lists. The numbers represented by the lists may contain leading zeros. If the numbers are equal then print 0.If the number represented by the first linked list is greater then print 1.If the number represented by the second linked
11 min read
Compare two strings represented as linked lists
Given two strings, represented as linked lists (every character is a node in a linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are the same, 1 if the first linked list is lexicographically greater, and -1 if the second string is lexicographically greater. Examples: Input: list1 = g->e-
7 min read
Javascript Program For Comparing Two Strings Represented As Linked Lists
Given two strings, represented as linked lists (every character is a node in a linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are the same, 1 if the first linked list is lexicographically greater, and -1 if the second string is lexicographically greater. Examples: Input: list1 = g->e-
2 min read
Multiply Large Numbers represented as Strings
Given two positive numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find product of these two numbers.Examples:  Input : num1 = 4154 num2 = 51454Output : 213739916 Input : num1 = 654154154151454545415415454 num2 = 63516561563156316545145146514654 Output : 4154962260395530977724371606999799700762043993
15+ min read
Add two numbers represented by Linked List without any extra space
Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is linked list representation of addition of two input numbers. Expected Space Complexity O(1). Examples: Input: L1 = 5 -> 6 -> 3 -> NULL L2 = 8 -> 4 -> 2 -> NULL Output: 1 -> 4 -> 0 -> 5 -> NULL Input: L1 = 1 ->
11 min read
Add two numbers represented as Linked List
Given two numbers represented as two lists, the task is to return the sum of two lists. Examples: Input: num1 = 4 -> 5, num2 = 3 -> 4 -> 5Output: 3 -> 9 -> 0 Explanation: Sum of 45 and 345 is 390. Input: num1 = 1 -> 2 -> 3, num2 = 9 -> 9 -> 9Output: 1 -> 1 -> 2 -> 2 Explanation: Sum of 123 and 999 is 1122. Table
15+ min read
Add Two Numbers represented as Linked List using Recursion
Given two numbers represented as two lists, the task is to return the sum of two lists using recursion. Examples: Input: num1 = 4 -> 5, num2 = 3 -> 4 -> 5Output: 3 -> 9 -> 0 Explanation: Sum of 45 and 345 is 390. Input: num1 = 1 -> 2 -> 3, num2 = 9 -> 9 -> 9Output: 1 -> 1 -> 2 -> 2 Explanation: Sum of 123 and 999
13 min read
Count prime numbers up to N that can be represented as a sum of two prime numbers
Given a positive integer N, the task is to find the count of prime numbers less than or equal to N that can be represented as a sum of two prime numbers. Examples: Input: N = 6Output: 1Explanation:5 is the only prime number over the range [1, 6] that can be represented as sum of 2 prime numbers i.e., 5 = 2 + 3, where 2, 3 and 5 are all primes.There
15+ min read
Add two numbers represented by two arrays
Given two array A[0....n-1] and B[0....m-1] of size n and m respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the number. In above case, answer is 337. Examples : Input : n = 3, m = 3
15+ min read
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to us
14 min read
Create a linked list from two linked lists by choosing max element at each position
Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped. Examples: Input: list1 = 5 -> 2 -> 3 -> 8 -> NULL list2 = 1 -> 7 -> 4 -> 5 -> NULL Output: 5 -> 7 -> 4
11 min read
Multiply two numbers of different base and represent product in another given base
Given two numbers N, M in the bases X, Y and another base P. The task is to find the product of N and M and represent the product in base P. Examples: Input: N = 101, M = 110, X = 2, Y = 2, P = 16Output:1EExplanation: NX * MY = (101)2 * (110)2 = (11110)2(11110)2 = (1E)16 Input: N = 101, M = A, X = 2, Y = 20, P = 16Output: 32Explanation: Nx = (101)2
10 min read
Russian Peasant (Multiply two numbers using bitwise operators)
Given two integers, write a function to multiply them without using multiplication operator.There are many other ways to multiply two numbers (For example, see this). One interesting method is the Russian peasant algorithm. The idea is to double the first number and halve the second number repeatedly till the second number doesn't become 1. In the
5 min read
Add two numbers represented by Stacks
Given two numbers N1 and N2 represented by two stacks, such that their most significant digits are present at the bottom of the stack, the task is to calculate and return the sum of the two numbers in the form of a stack. Examples: Input: N1={5, 8, 7, 4}, N2={2, 1, 3} Output: {6, 0, 8, 7}Explanation:Step 1: Popped element from N1(= 4) + Popped elem
8 min read
Sum of two numbers where one number is represented as array of digits
Given an array arr[] of digits and an integer K, the task is to find num(arr) + K where num(arr) is the number formed by concatenating all the digits of the array. Examples: Input: arr[] = {2, 7, 4}, K = 181 Output: 455 274 + 181 = 455 Input: arr[] = {6}, K = 815 Output: 821 6 + 815 = 821 Approach: Start traversing the digits array from the end and
10 min read
Find two Fibonacci numbers whose sum can be represented as N
Given an even number N, the task is to find two Fibonacci numbers whose sum can be represented as N. There may be several combinations possible. Print only first such pair. If there is no solution then print -1.Examples: Input: N = 90 Output: 1, 89 Explanation: The first pair with whose sum is equal to 90 is {1, 89}Input: N = 74 Output: -1 Approach
6 min read
Count integers up to N which can be represented as sum of two or more consecutive numbers
Given a positive integer N, the task is to count the number of integers upto N which can be represented as the sum of two or more consecutive numbers. Examples: Input: N = 7Output: 4Explanation: In the range [1, 7]: {3, 5, 6, 7} can be represented as sum of consecutive numbers. 3 = 1 + 25 = 2 + 36 = 1 + 2 + 37 = 3 + 4 Input: N = 15Output: 11 Naive
7 min read
Count of numbers in range [L, R] which can be represented as sum of two perfect powers
Given a range [L, R], the task is to find the count of numbers in the range [L, R] that can be expressed as a sum of two perfect powers. Examples: Input: L = 0, R = 1Output: 2Explanation:The valid numbers are: 1 as it can be expressed as, 1 = 12 + 02.0 as it can be expressed as, 0 = 02 + 02. Therefore, the count of such numbers is 2. Input: L = 5,
8 min read
Check if given number can be represented as sum of two great numbers
We are given a number N. We need to check if the given number N can be represented as sum of two Great numbers. If yes then print those two great numbers else print no. Great numbers are those which are represented in the form : ((b)*(b+1)*(2*b+1))/6 where b is a natural number. Examples: Input : N = 35Output : 5 and 30Input : 105Output : 14 and 91
7 min read
Add one to a number represented as linked list | Set 2
Given a singly linked list which represents a number where each node contains only one digit [0 - 9]. The task is to add 1 to the number represented by the given linked list and print the new linked list.Examples: Input: 1 -> 2 -> 9 -> 9 -> NULL Output: Original list is : 1 2 9 9 Resultant list is : 1 3 0 0 Input: 9 -> 9 -> 9 -
10 min read
Reverse all the word in a String represented as a Linked List
Given a Linked List which represents a sentence S such that each node represents a letter, the task is to reverse the sentence without reversing individual words. For example, for a given sentence "I love Geeks for Geeks", the Linked List representation is given as: I-> ->l->o->v->e-> ->G->e->e->k->s-> ->f-
15 min read
Add number and its reverse represented by Linked List
Given a number represented by a linked list, write a function that returns the sum of that number with its reverse form, and returns the resultant linked list. Note: Avoid modifying the original linked list. Examples: Input: 1->2->3->4 Output: 5->5->5->5Explanation: Input list: 1 2 3 4Reverse list: + 4 3 2 1resultant list: 5 5 5 5
12 min read
Subtract 1 from a number represented as Linked List
Given the head of the linked list representing a positive integer, the task is to print the updated linked list after subtracting 1 from it. Examples: Input: LL = 1 -> 2 -> 3 -> 4Output: 1 -> 2 -> 3 -> 3 Input: LL = 1 -> 2Output: 1 -> 1 Approach: The given problem can be solved by using recursion. Follow the steps below to s
15+ min read
Article Tags :
Practice Tags :