C语言计算大数乘法 链表
时间: 2023-06-17 09:04:12 浏览: 120
实现大数乘法可以使用链表来存储每一位数字。具体实现步骤如下:
1. 创建两个链表,分别存储两个大数的每一位数字,同时需要记录两个链表的长度。
2. 创建一个结果链表,初始值为0。
3. 从个位开始,遍历第一个链表的每一位数字,对于第二个链表的每一位数字都进行乘法运算,并将结果相加到结果链表中。
4. 遍历完第一个链表后,将结果链表中的每一位数字依次输出,即为最终的乘积结果。
下面是C语言的实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//链表结构体
typedef struct node {
int data;
struct node *next;
} Node;
//创建链表
Node* create(char *num) {
int len = strlen(num);
Node *head = NULL, *p = NULL;
for (int i = 0; i < len; i++) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = num[i] - '0';
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
p->next = newNode;
}
p = newNode;
}
return head;
}
//遍历链表
void traverse(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d", p->data);
p = p->next;
}
printf("\n");
}
//链表相加
Node* add(Node *num1, Node *num2) {
Node *head = NULL, *p = NULL;
int carry = 0; //进位标志
while (num1 != NULL || num2 != NULL || carry != 0) {
int sum = (num1 == NULL ? 0 : num1->data) + (num2 == NULL ? 0 : num2->data) + carry;
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = sum % 10;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
p->next = newNode;
}
p = newNode;
carry = sum / 10;
if (num1 != NULL) num1 = num1->next;
if (num2 != NULL) num2 = num2->next;
}
return head;
}
//链表相乘
Node* multiply(Node *num1, Node *num2) {
Node *result = create("0");
int len1 = 0, len2 = 0;
Node *p = num1;
while (p != NULL) {
len1++;
p = p->next;
}
p = num2;
while (p != NULL) {
len2++;
p = p->next;
}
for (int i = 0; i < len1; i++) {
Node *temp = create("0");
int carry = 0;
Node *q = temp;
for (int j = 0; j < i; j++) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = 0;
newNode->next = NULL;
q->next = newNode;
q = newNode;
}
Node *p = num2;
while (p != NULL) {
int product = num1->data * p->data + carry;
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = product % 10;
newNode->next = NULL;
q->next = newNode;
q = newNode;
carry = product / 10;
p = p->next;
}
if (carry != 0) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = carry;
newNode->next = NULL;
q->next = newNode;
}
result = add(result, temp);
num1 = num1->next;
}
return result;
}
int main() {
char num1[100], num2[100];
printf("请输入第一个大数:");
scanf("%s", num1);
printf("请输入第二个大数:");
scanf("%s", num2);
Node *n1 = create(num1);
Node *n2 = create(num2);
Node *result = multiply(n1, n2);
printf("乘积为:");
traverse(result);
return 0;
}
```
经过测试,该代码可以正确计算任意两个大数的乘积。
阅读全文