# Multiply two numbers represented as linked lists into a third list in C++

C++Server Side ProgrammingProgramming

Given two linked lists with digits in it. We need to multiply two numbers formed by the linked list. It can be done easily by forming the numbers from the two linked lists. Let's see an example.

Input

1 -> 2 -> NULL
2 -> 3 -> NULL

Output

2 -> 7 -> 6 -> NULL

## Algorithm

• Initialise the two linked lists.
• Initialise two variables with 0 to store the two numbers.
• Iterate over the two linked lists.
• Add each digit to the respective number variable at the end.
• Multiply the resultant numbers and store the result in a variable.
• Create a new list with the result.
• Print the new list.

## Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void addNewNode(struct Node** head, int new_data) {
struct Node* newNode = new Node;
newNode->data = new_data;
}
int _1 = 0, _2 = 0;
_1 = _1 * 10 + firstHead->data;
}
_2 = _2 * 10 + secondHead->data;
}
}
int result = _1 * _2;
while (result) {
result /= 10;
}
}
void printLinkedList(struct Node *node) {
while(node != NULL) {
cout << node->data << "->";
node = node->next;
}
cout << "NULL" << endl;
}
int main(void) {
struct Node* firstHead = NULL;
struct Node* secondHead = NULL;
return 0;
}

## Output

If you run the above code, then you will get the following result.

3->2->1->NULL
2->1->NULL
6->7->4->1->NULL
Published on 03-Jul-2021 04:37:17