用c语言单向链表超长正整数的加法,设计一个程序实现两个任意长的整数求和运算
时间: 2023-05-22 14:02:09 浏览: 154
好的,以下是一个用 C 语言实现的单向链表超长正整数加法的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int digit;
struct Node *next;
} Node;
Node *create_node(int digit) {
Node *node = (Node *) malloc(sizeof(Node));
node->digit = digit;
node->next = NULL;
return node;
}
Node *add_digit(Node *head, int digit) {
Node *node = create_node(digit);
node->next = head;
return node;
}
Node *add_long_int(Node *num1, Node *num2) {
Node *result = NULL;
int carry = 0;
while (num1 != NULL || num2 != NULL) {
int sum = carry;
if (num1 != NULL) {
sum += num1->digit;
num1 = num1->next;
}
if (num2 != NULL) {
sum += num2->digit;
num2 = num2->next;
}
carry = sum / 10;
result = add_digit(result, sum % 10);
}
if (carry > 0) {
result = add_digit(result, carry);
}
return result;
}
void print_long_int(Node *num) {
while (num != NULL) {
printf("%d", num->digit);
num = num->next;
}
printf("\n");
}
int main() {
char str1[1000], str2[1000];
printf("请输入两个任意长的整数:\n");
scanf("%s%s", str1, str2);
int len1 = strlen(str1), len2 = strlen(str2);
Node *num1 = NULL, *num2 = NULL;
for (int i = len1 - 1; i >= 0; i--) {
num1 = add_digit(num1, str1[i] - '0');
}
for (int i = len2 - 1; i >= 0; i--) {
num2 = add_digit(num2, str2[i] - '0');
}
Node *result = add_long_int(num1, num2);
printf("结果为:\n");
print_long_int(result);
return 0;
}
```
这个程序可以读入两个任意长的整数,用单向链表存储,然后实现加法运算,最后输出结果。
阅读全文