用 C++ 乘以由链表表示的两个数字
给定两个其中带有数字的链表。我们需要将两个链表组成的两个数字相乘。可以通过根据两个链表组成数字,轻松完成此操作。让我们看一个示例。
输入
1 -> 2 -> NULL 2 -> 3 -> NULL
输出
2 -> 7 -> 6 -> NULL
算法
- 初始化两个链表。
- 初始化两个变量为 0,以存储所表示的两个数字。
- 遍历两个链表。
- 将每个数字添加到末尾的相应数字变量。
- 将结果数字相乘,并将结果存储在一个变量中。
- 使用结果创建一个新的列表。
- 打印新列表。
实现
以下是在 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;
newNode->next = *head;
*head = newNode;
}
void multiplyTwoLinkedLists(struct Node* firstHead, struct Node* secondHead
, struct Node** newLinkedListHead) {
int _1 = 0, _2 = 0;
while (firstHead || secondHead) {
if (firstHead) {
_1 = _1 * 10 + firstHead->data;
firstHead = firstHead->next;
}
if (secondHead) {
_2 = _2 * 10 + secondHead->data;
secondHead = secondHead->next;
}
}
int result = _1 * _2;
while (result) {
addNewNode(newLinkedListHead, result % 10);
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;
addNewNode(&firstHead, 1);
addNewNode(&firstHead, 2);
addNewNode(&firstHead, 3);
printLinkedList(firstHead);
addNewNode(&secondHead, 1);
addNewNode(&secondHead, 2);
printLinkedList(secondHead);
struct Node* newLinkedListHead = NULL;
multiplyTwoLinkedLists(firstHead, secondHead, &newLinkedListHead);
printLinkedList(newLinkedListHead);
return 0;
}输出
如果运行上述代码,将获得以下结果。
3->2->1->NULL 2->1->NULL 6->7->4->1->NULL
广告
数据结构
网络通信
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP