Open In App

Multiply two numbers represented as linked lists into a third list

Improve
Improve
Like Article
Like
Save
Share
Report

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->9->8->0->1->8->1
 

We have already discussed a solution in below post. 
Multiply two numbers represented by Linked Lists

The solution discussed above stores result in an integer. Here we store result in a third list so that large numbers can be handled.
Remember old school multiplication? we imitate that process. On paper, we take the last digit of a number and multiply with the second number and write the product. Now leave the last column and same way each digit of one number is multiplied with every digit of other number and every time result is written by leaving one last column. then add these columns that forms the number. Now assume these columns as nodes of the resultant linked list. We make resultant linked list in reversed fashion. 

Algorithm:

Reverse both linked lists
Make a linked list of maximum result size (m + n + 1)
For each node of one list
  For each node of second list
   a) Multiply nodes
   b) Add digit in result LL at corresponding 
      position
   c) Now resultant node itself can be higher
      than one digit
   d) Make carry for next node
  Leave one last column means next time start
From next node in result list
Reverse the resulted linked list

Implementation:

C++




// C++ program to Multiply two numbers
// represented as linked lists
#include <bits/stdc++.h>
using namespace std;
 
// Linked list Node
struct Node {
    int data;
    struct Node* next;
};
 
// Function to create a new Node
// with given data
struct 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 List
void push(struct Node** head_ref, int new_data)
{
    // allocate Node
    struct Node* new_node = newNode(new_data);
 
    // link the old list of the new Node
    new_node->next = (*head_ref);
 
    // move the head to point to the new Node
    (*head_ref) = new_node;
}
 
// Function to reverse the linked list and return
// its length
int reverse(struct Node** head_ref)
{
    struct Node* prev = NULL;
    struct Node* current = *head_ref;
    struct Node* next;
    int len = 0;
    while (current != NULL) {
        len++;
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    *head_ref = prev;
    return len;
}
 
// Function to make an empty linked list of
// given size
struct Node* make_empty_list(int size)
{
    struct Node* head = NULL;
    while (size--)
        push(&head, 0);
    return head;
}
 
// Multiply contents of two linked lists => store
// in another list and return its head
struct Node* multiplyTwoLists(struct Node* first,
                        struct Node* second)
{
    // reverse the lists to multiply from end
    // m and n lengths of linked lists to make
    // and empty list
    int m = reverse(&first), n = reverse(&second);
 
    // make a list that will contain the result
    // of multiplication.
    // m+n+1 can be max size of the list
    struct Node* result = make_empty_list(m + n + 1);
 
    // pointers for traverse linked lists and also
    // to reverse them after
    struct Node *second_ptr = second,
        *result_ptr1 = result, *result_ptr2, *first_ptr;
 
    // multiply each Node of second list with first
    while (second_ptr) {
 
        int carry = 0;
 
        // each time we start from the next of Node
        // from which we started last time
        result_ptr2 = result_ptr1;
 
        first_ptr = first;
 
        while (first_ptr) {
 
            // multiply a first list's digit with a
            // current second list's digit
            int mul = first_ptr->data * second_ptr->data
                    + carry;
 
            // Assign the product to corresponding Node
            // of result
            result_ptr2->data += mul % 10;
 
            // now resultant Node itself can have more
            // than 1 digit
            carry = mul / 10 + result_ptr2->data / 10;
            result_ptr2->data = result_ptr2->data % 10;
 
            first_ptr = first_ptr->next;
            result_ptr2 = result_ptr2->next;
        }
 
        // if carry is remaining from last multiplication
        if (carry > 0) {
            result_ptr2->data += carry;
        }
 
        result_ptr1 = result_ptr1->next;
        second_ptr = second_ptr->next;
    }
 
    // reverse the result_list as it was populated
    // from last Node
    reverse(&result);
    reverse(&first);
    reverse(&second);
 
    // remove if there are zeros at starting
    while (result->data == 0) {
        struct Node* temp = result;
        result = result->next;
        free(temp);
    }
 
    // Return head of multiplication list
    return result;
}
 
// A utility function to print a linked list
void printList(struct Node* Node)
{
    while (Node != NULL) {
        cout << Node->data;
        if (Node->next)
            cout<<"->";
        Node = Node->next;
    }
    cout << endl;
}
 
// Driver program to test above function
int main(void)
{
    struct Node* first = NULL;
    struct Node* second = NULL;
 
    // create first list 9->9->9->4->6->9
    push(&first, 9);
    push(&first, 6);
    push(&first, 4);
    push(&first, 9);
    push(&first, 9);
    push(&first, 9);
    cout<<"First List is: ";
    printList(first);
 
    // create second list 9->9->8->4->9
    push(&second, 9);
    push(&second, 4);
    push(&second, 8);
    push(&second, 9);
    push(&second, 9);
    cout<<"Second List is: ";
    printList(second);
 
    // Multiply the two lists and see result
    struct Node* result = multiplyTwoLists(first, second);
    cout << "Resultant list is: ";
    printList(result);
 
    return 0;
}
 
// This code is contributed by SHUBHAMSINGH10


C




// C program to Multiply two numbers
// represented as linked lists
#include <stdio.h>
#include <stdlib.h>
 
// Linked list Node
struct Node {
    int data;
    struct Node* next;
};
 
// Function to create a new Node
// with given data
struct 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 List
void push(struct Node** head_ref, int new_data)
{
    // allocate Node
    struct Node* new_node = newNode(new_data);
 
    // link the old list of the new Node
    new_node->next = (*head_ref);
 
    // move the head to point to the new Node
    (*head_ref) = new_node;
}
 
// Function to reverse the linked list and return
// its length
int reverse(struct Node** head_ref)
{
    struct Node* prev = NULL;
    struct Node* current = *head_ref;
    struct Node* next;
    int len = 0;
    while (current != NULL) {
        len++;
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    *head_ref = prev;
    return len;
}
 
// Function to make an empty linked list of
// given size
struct Node* make_empty_list(int size)
{
    struct Node* head = NULL;
    while (size--)
        push(&head, 0);
    return head;
}
 
// Multiply contents of two linked lists => store
// in another list and return its head
struct Node* multiplyTwoLists(struct Node* first,
                           struct Node* second)
{
    // reverse the lists to multiply from end
    // m and n lengths of linked lists to make
    // and empty list
    int m = reverse(&first), n = reverse(&second);
 
    // make a list that will contain the result
    // of multiplication.
    // m+n+1 can be max size of the list
    struct Node* result = make_empty_list(m + n + 1);
 
    // pointers for traverse linked lists and also
    // to reverse them after
    struct Node *second_ptr = second,
          *result_ptr1 = result, *result_ptr2, *first_ptr;
 
    // multiply each Node of second list with first
    while (second_ptr) {
 
        int carry = 0;
 
        // each time we start from the next of Node
        // from which we started last time
        result_ptr2 = result_ptr1;
 
        first_ptr = first;
 
        while (first_ptr) {
 
            // multiply a first list's digit with a
            // current second list's digit
            int mul = first_ptr->data * second_ptr->data
                      + carry;
 
            // Assign the product to corresponding Node
            // of result
            result_ptr2->data += mul % 10;
 
            // now resultant Node itself can have more
            // than 1 digit
            carry = mul / 10 + result_ptr2->data / 10;
            result_ptr2->data = result_ptr2->data % 10;
 
            first_ptr = first_ptr->next;
            result_ptr2 = result_ptr2->next;
        }
 
        // if carry is remaining from last multiplication
        if (carry > 0) {
            result_ptr2->data += carry;
        }
 
        result_ptr1 = result_ptr1->next;
        second_ptr = second_ptr->next;
    }
 
    // reverse the result_list as it was populated
    // from last Node
    reverse(&result);
    reverse(&first);
    reverse(&second);
 
    // remove if there are zeros at starting
    while (result->data == 0) {
        struct Node* temp = result;
        result = result->next;
        free(temp);
    }
 
    // Return head of multiplication list
    return result;
}
 
// A utility function to print a linked list
void 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 function
int main(void)
{
    struct Node* first = NULL;
    struct Node* second = NULL;
 
    // create first list 9->9->9->4->6->9
    push(&first, 9);
    push(&first, 6);
    push(&first, 4);
    push(&first, 9);
    push(&first, 9);
    push(&first, 9);
    printf("First List is: ");
    printList(first);
 
    // create second list 9->9->8->4->9
    push(&second, 9);
    push(&second, 4);
    push(&second, 8);
    push(&second, 9);
    push(&second, 9);
    printf("Second List is: ");
    printList(second);
 
    // Multiply the two lists and see result
    struct Node* result = multiplyTwoLists(first, second);
    printf("Resultant list is: ");
    printList(result);
 
    return 0;
}


Java




// Java program to multiply two numbers
// represented as linked lists
import java.io.*;
 
// Node class
class Node {
  int data;
  Node next;
 
  // Constructor to create a new node
  public Node(int data)
  {
    this.data = data;
    this.next = null;
  }
}
 
// LinkedList class
class LinkedList {
  Node head;
 
  // Constructor to initialize an empty linked list
  public LinkedList() { this.head = null; }
 
  // Method to add a new node at the beginning of the list
  public void push(int newData)
  {
    // Create a new node
    Node newNode = new Node(newData);
 
    // Make next of new node as head
    newNode.next = head;
 
    // Move the head to point to new node
    head = newNode;
  }
 
  // Method to print the linked list
  public void printList()
  {
    // Object to iterate the list
    Node ptr = head;
 
    if (head.data == 0) {
      ptr = head.next;
    }
 
    // Loop to iterate the list
    while (ptr != null) {
      System.out.print(ptr.data + " -> ");
 
      // Moving the iterating object to the next node
      ptr = ptr.next;
    }
 
    System.out.println();
  }
}
 
class GFG {
 
  // Function to reverse the linked list and return its
  // length
  public static int reverse(LinkedList headRef)
  {
    // Initializing prev and current at null and
    // starting node respectively
    Node prev = null;
    Node current = headRef.head;
 
    int Len = 0;
 
    // Loop to reverse the link of each node in the list
    while (current != null) {
      Len++;
      Node next = current.next;
      current.next = prev;
      prev = current;
      current = next;
    }
 
    // Assigning new starting object to main head object
    headRef.head = prev;
 
    // Returning the length of linked list
    return Len;
  }
 
  // Function to define an empty linked list of given size
  // and each element as zero
  public static LinkedList makeEmptyList(int size)
  {
    LinkedList head = new LinkedList();
 
    while (size-- > 0) {
      head.push(0);
    }
 
    // Returns the head object
    return head;
  }
 
  // Multiply contents of two linked lists and store it in
  // another list and return its head
  public static LinkedList
    multiplyTwoLists(LinkedList first, LinkedList second)
  {
    // Reverse the lists to multiply from the end and
    // calculate their lengths
    int m = reverse(first);
    int n = reverse(second);
 
    // Make a list that will contain the result of the
    // multiplication m + n + 1 can be the max size of
    // the list
    LinkedList result = makeEmptyList(m + n + 1);
 
    // Objects to iterate the lists and also to reverse
    // them after
    Node secondPtr = second.head;
    Node resultPtr1 = result.head;
 
    // Multiply each node of second list with first
    while (secondPtr != null) {
      int carry = 0;
 
      // Each time we start from the next node from
      // which we started last time
      Node resultPtr2 = resultPtr1;
      Node firstPtr = first.head;
 
      // Multiply a first list's digit with a current
      // second list's digit
      while (firstPtr != null) {
        int mul = (firstPtr.data * secondPtr.data
                   + carry);
 
        // Assign the product to corresponding node
        // of result
        resultPtr2.data += mul % 10;
 
        // Now resultant node itself can have more
        // than one digit
        carry = (mul / 10) + (resultPtr2.data / 10);
        resultPtr2.data = resultPtr2.data % 10;
 
        firstPtr = firstPtr.next;
        resultPtr2 = resultPtr2.next;
      }
 
      // If carry is remaining from last
      // multiplication
      if (carry > 0) {
        resultPtr2.data += carry;
      }
 
      resultPtr1 = resultPtr1.next;
      secondPtr = secondPtr.next;
    }
 
    // Reverse the result list
    reverse(result);
 
    // Return the head of result list
    return result;
  }
 
  public static void main(String[] args)
  {
 
    // Creating the first list
    LinkedList first = new LinkedList();
    first.push(9);
    first.push(6);
    first.push(4);
    first.push(9);
    first.push(9);
    first.push(9);
    System.out.print("First List is: ");
    first.printList();
 
    // Creating the second list
    LinkedList second = new LinkedList();
    second.push(9);
    second.push(4);
    second.push(8);
    second.push(9);
    second.push(9);
    System.out.print("Second List is: ");
    second.printList();
 
    // Multiplying the lists
    LinkedList result = multiplyTwoLists(first, second);
    System.out.print("Resultant List is: ");
    result.printList();
  }
}
 
// This code is contributed by lokesh.


Python3




# Python3 program to multiply two numbers
# represented as linked lists
 
# Node class
class Node:
     
    # Function to initialize the node object
    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
 
    # This function insert a new 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 new Node as head
        new_node.next = self.head
 
        # Move the head to point to new Node
        self.head = new_node
         
    # Method to print the linked list
    def printList(self):
 
        # Object to iterate
        # the list
        ptr = self.head
 
        # Loop to iterate list
        while(ptr != None):
            print(ptr.data, '->', end = '')
 
            # Moving the iterating object
            # to next node
            ptr = ptr.next
             
        print()
 
# Function to reverse the linked
# list and return its length
def reverse(head_ref):
 
    # Initialising prev and current
    # at None and starting node
    # respectively.
    prev = None
    current = head_ref.head
 
    Len = 0
 
    # Loop to reverse the link
    # of each node in the list
    while(current != None):
        Len += 1
        Next = current.next
        current.next = prev
        prev = current
        current = Next
 
    # Assigning new starting object
    # to main head object.
    head_ref.head = prev
 
    # Returning the length of
    # linked list.
    return Len
 
# Function to define an empty
# linked list of given size and
# each element as zero.
def make_empty_list(size):
     
    head = LinkedList()
     
    while(size):
        head.push(0)
        size -= 1
 
    # Returns the head object.
    return head
 
# Multiply contents of two linked
# list store it in other list and
# return its head.
def multiplyTwoLists(first, second):
 
    # Reverse the list to multiply from
    # end m and n lengths of linked list
    # to make and empty list
    m = reverse(first)
    n = reverse(second)
 
    # Make a list that will contain the
    # result of multiplication.
    # m+n+1 can be max size of the list.
    result = make_empty_list(m + n + 1)
 
    # Objects for traverse linked list
    # and also to reverse them after.
    second_ptr = second.head
    result_ptr1 = result.head
 
    # Multiply each node of second
    # list with first.
    while(second_ptr != None):
        carry = 0
 
        # Each time we start from next
        # node from which we started last
        # time.
        result_ptr2 = result_ptr1
        first_ptr = first.head
 
        while(first_ptr != None):
             
            # Multiply a first list's digit
            # with a current second list's digit.
            mul = ((first_ptr.data) *
                  (second_ptr.data) + carry)
 
            # Assign the product to corresponding
            # node of result.
            result_ptr2.data += mul % 10
 
            # Now resultant node itself can have
            # more than one digit.
            carry = ((mul // 10) +
                     (result_ptr2.data // 10))
            result_ptr2.data = result_ptr2.data % 10
 
            first_ptr = first_ptr.next
            result_ptr2 = result_ptr2.next
 
        # If carry is remaining from
        # last multiplication
        if(carry > 0):
            result_ptr2.data += carry
 
        result_ptr1 = result_ptr1.next
        second_ptr = second_ptr.next
 
    # Reverse the result_list as it
    # was populated from last node
    reverse(result)
    reverse(first)
    reverse(second)
 
    # Remove starting nodes
    # containing zeroes.
    start = result.head
    while(start.data == 0):
        result.head = start.next
        start = start.next
 
    # Return the resultant multiplicated
    # linked list.
    return result
 
# Driver code
if __name__=='__main__':
 
    first = LinkedList()
    second = LinkedList()
 
    # Pushing elements at start of
    # first linked list.
    first.push(9)
    first.push(6)
    first.push(4)
    first.push(9)
    first.push(9)
    first.push(9)
 
    # Printing first linked list
    print("First list is: ", end = '')
    first.printList()
 
    # Pushing elements at start of
    # second linked list.
    second.push(9)
    second.push(4)
    second.push(8)
    second.push(9)
    second.push(9)
 
    # Printing second linked list.
    print("Second List is: ", end = '')
    second.printList()
 
    # Multiply two linked list and
    # print the result.
    result = multiplyTwoLists(first, second)
    print("Resultant list is: ", end = '')
    result.printList()
     
# This code is contributed by Amit Mangal


C#




// C# program to multiply two numbers
// represented as linked lists
using System;
 
// Node class
class Node
{
  public int data;
  public Node next;
 
  // Constructor to create a new node
  public Node(int data)
  {
    this.data = data;
    this.next = null;
  }
}
 
// LinkedList class
class LinkedList
{
  public Node head;
 
  // Constructor to initialize an empty linked list
  public LinkedList()
  {
    this.head = null;
  }
 
  // Method to add a new node at the beginning of the list
  public void Push(int newData)
  {
    // Create a new node
    Node newNode = new Node(newData);
 
    // Make next of new node as head
    newNode.next = head;
 
    // Move the head to point to new node
    head = newNode;
  }
 
  // Method to print the linked list
  public void PrintList()
  {
    // Object to iterate the list
    Node ptr = head;
 
    if (head.data == 0)
    {
      ptr = head.next;
    }
 
    // Loop to iterate the list
    while (ptr != null)
    {
      Console.Write(ptr.data + " -> ");
 
      // Moving the iterating object to the next node
      ptr = ptr.next;
    }
 
    Console.WriteLine();
  }
}
 
class GFG
{
 
  // Function to reverse the linked list and return its
  // length
  public static int Reverse(LinkedList headRef)
  {
    // Initializing prev and current at null and
    // starting node respectively
    Node prev = null;
    Node current = headRef.head;
 
    int Len = 0;
 
    // Loop to reverse the link of each node in the list
    while (current != null)
    {
      Len++;
      Node next = current.next;
      current.next = prev;
      prev = current;
      current = next;
    }
 
    // Assigning new starting object to main head object
    headRef.head = prev;
 
    // Returning the length of linked list
    return Len;
  }
 
  // Function to define an empty linked list of given size
  // and each element as zero
  public static LinkedList MakeEmptyList(int size)
  {
    LinkedList head = new LinkedList();
 
    while (size-- > 0)
    {
      head.Push(0);
    }
 
    // Returns the head object
    return head;
  }
 
  // Multiply contents of two linked lists and store it in
  // another list and return its head
  public static LinkedList
    MultiplyTwoLists(LinkedList first, LinkedList second)
  {
    // Reverse the lists to multiply from the end and
    // calculate their lengths
    int m = Reverse(first);
    int n = Reverse(second);
 
    // Make a list that will contain the result of the
    // multiplication m + n + 1 can be the max size of
    // the list
    LinkedList result = MakeEmptyList(m + n + 1);
 
    // Objects to iterate the lists and also to reverse
    // them after
    Node secondPtr = second.head;
    Node resultPtr1 = result.head;
 
    // Multiply each node of second list with first
    while (secondPtr != null)
    {
      int carry = 0;
 
      // Each time we start from the next node from
      // which we started last time
      Node resultPtr2 = resultPtr1;
      Node firstPtr = first.head;
 
      // Multiply a first list's digit with a current
      // second list's digit
      while (firstPtr != null)
      {
        int mul = (firstPtr.data * secondPtr.data
                   + carry);
 
        // Assign the product to corresponding node
        // of result
        resultPtr2.data += mul % 10;
 
        // Now resultant node itself can have more
        // than one digit
        carry = (mul / 10) + (resultPtr2.data / 10);
        resultPtr2.data = resultPtr2.data % 10;
 
        firstPtr = firstPtr.next;
        resultPtr2 = resultPtr2.next;
      }
 
      // If carry is remaining from last
      // multiplication
      if (carry > 0)
      {
        resultPtr2.data += carry;
      }
 
      resultPtr1 = resultPtr1.next;
      secondPtr = secondPtr.next;
    }
 
    // Reverse the result list
    Reverse(result);
 
    // Return the head of result list
    return result;
  }
 
  public static void Main(String[] args)
  {
 
    // Creating the first list
    LinkedList first = new LinkedList();
    first.Push(9);
    first.Push(6);
    first.Push(4);
    first.Push(9);
    first.Push(9);
    first.Push(9);
    Console.Write("First List is: ");
    first.PrintList();
 
    // Creating the second list
    LinkedList second = new LinkedList();
    second.Push(9);
    second.Push(4);
    second.Push(8);
    second.Push(9);
    second.Push(9);
    Console.Write("Second List is: ");
    second.PrintList();
 
    // Multiplying the lists
    LinkedList result = MultiplyTwoLists(first, second);
    Console.Write("Resultant List is: ");
    result.PrintList();
  }
}


Javascript




// JavaScript program to multiply two numbers
// represented as linked lists
// linked list node
class Node{
    constructor(data){
        this.data = data;
        this.next = null;
    }
}
 
// function to create a new node
// with given data
function newNode(data){
    return new Node(data);
}
 
// function to insert a node at the
// beginning of the linked list
function push(head_ref, new_data){
    // allocated node and put data
    let new_node = new Node(new_data);
     
    // link to old list of the new node
    new_node.next = head_ref;
     
    // move the head to point to the new node
    head_ref = new_node;
    return head_ref;
}
 
// function to reverse the linked list
// and return its length
function reverse(head_ref){
    let prev = null;
    let current = head_ref;
    let next;
    while(current != null){
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
    head_ref = prev;
    return head_ref;
}
 
// function to make an empty linked list of
// given size
function make_empty_list(size){
    let head = null;
    while(size--){
        head = push(head, 0);
    }
    return head;
}
 
// function return the length of linked list
function len(head){
    let n = 0;
    while(head != null){
        n++;
        head = head.next;
    }
    return n;
}
 
// multiply contents of two linked lists => store
// in another list and return its head
function multiplyTwoLists(first, second){
    // reverse the lists to multiply from end
    // m and n lengths of linked lists to make
    // and empty list
    first = reverse(first);
    second = reverse(second);
     
    let m = len(first);
    let n = len(second);
     
    // make a list that will contain the result
    // of multiplication.
    // m+n+1 can be max size of the list
    let result = make_empty_list(m+n+1);
     
    // pointers for traverse linked lists and also
    // to reverse them after
    let second_ptr = second;
    let result_ptr1 = result;
    let result_ptr2;
    let first_ptr;
     
    // multiply each node of second list with first
    while(second_ptr){
        let carry = 0;
         
        // each time we start from the next of node
        // from which we started last time
        result_ptr2 = result_ptr1;
         
        first_ptr = first;
         
        while(first_ptr){
            // multiply a first list's digit with a
            // current second list's digit
            let mul = first_ptr.data * second_ptr.data + carry;
             
            // assign the product to corresponding node
            // of result
            result_ptr2.data += mul % 10;
             
            // now resultant node itself can have more
            // than 1 digit
            carry = parseInt(mul / 10) + parseInt(result_ptr2.data/10);
            result_ptr2.data = result_ptr2.data % 10;
             
            first_ptr = first_ptr.next;
            result_ptr2 = result_ptr2.next;
        }
        // if carry is remaining from last multiplication
        if (carry > 0) {
            result_ptr2.data += carry;
        }
  
        result_ptr1 = result_ptr1.next;
        second_ptr = second_ptr.next;
    }
    // reverse the result_list as it was populated
    // from last Node
    result = reverse(result);
    first = reverse(first);
    second = reverse(second);
     
    // remove if there are zeros at starting
    while (result.data == 0) {
        let temp = result;
        result = result.next;
    }
  
    // Return head of multiplication list
    return result;
}
 
// a utility function to print a linked list
function printList(Node){
    while(Node != null){
        console.log(Node.data);
        if(Node.next)
            console.log("->");
        Node = Node.next;
    }
    console.log("\n");
}
 
// driver code to test above functions
let first = null;
let second = null;
 
// create first list 9->9->9->4->6->9
first = push(first, 9);
first = push(first, 6);
first = push(first, 4);
first = push(first, 9);
first = push(first, 9);
first = push(first, 9);
console.log("First List is : ");
printList(first);
 
// create second list 9->9->8->4->9
second = push(second, 9);
second = push(second, 4);
second = push(second, 8);
second = push(second, 9);
second = push(second, 9);
console.log("Second List is : ");
printList(second);
 
// multiply the two lists and see result
let result = multiplyTwoLists(first, second);
console.log("Resultant list is : ");
printList(result);
 
// THIS  CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


Output: 

First List is: 9->9->9->4->6->9
Second List is: 9->9->8->4->9
Resultant list is: 9->9->7->9->5->9->8->0->1->8->1

Time complexity: O(M+N) where M and N are size of given two linked lists respectively

Auxiliary Space: O(1)

Note: we can take care of resultant node that can have more than 1 digit outside the loop just traverse the result list and add carry to next digit before reversing.



Last Updated : 20 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads