C语言实现读取两个超大数存入链表并求和,不用考虑进位的情况
时间: 2024-02-25 22:58:44 浏览: 87
以下是一个示例代码,实现读取两个超大数并存入链表,再对它们进行求和(不考虑进位):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int num;
struct Node* next;
} Node;
Node* createNode(int num) {
Node* node = (Node*)malloc(sizeof(Node));
node->num = num;
node->next = NULL;
return node;
}
Node* addNode(Node* head, int num) {
Node* node = createNode(num);
if (head == NULL) {
head = node;
} else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
}
return head;
}
Node* readNumber() {
char buf[1024];
scanf("%s", buf);
int len = strlen(buf);
Node* head = NULL;
for (int i = len - 1; i >= 0; i--) {
int num = buf[i] - '0';
head = addNode(head, num);
}
return head;
}
Node* sum(Node* num1, Node* num2) {
Node* result = NULL;
Node* current1 = num1;
Node* current2 = num2;
while (current1 != NULL || current2 != NULL) {
int sum = 0;
if (current1 != NULL) {
sum += current1->num;
current1 = current1->next;
}
if (current2 != NULL) {
sum += current2->num;
current2 = current2->next;
}
result = addNode(result, sum);
}
return result;
}
void printNumber(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d", current->num);
current = current->next;
}
printf("\n");
}
int main() {
printf("Enter the first number: ");
Node* num1 = readNumber();
printf("Enter the second number: ");
Node* num2 = readNumber();
Node* result = sum(num1, num2);
printf("Result: ");
printNumber(result);
return 0;
}
```
这段代码中,首先定义了一个 `Node` 结构体,用于存储链表节点的信息。`createNode` 函数用于创建新节点,`addNode` 函数用于将节点添加到链表中。`readNumber` 函数用于从标准输入中读取一个超大数,并将其存入链表中,这里假设输入的数都是合法的非负整数。`sum` 函数用于对两个链表中的数进行求和,不考虑进位。最后,`printNumber` 函数用于将链表中的数输出到标准输出中。在 `main` 函数中,首先读取两个超大数,然后对它们进行求和,并将结果输出到标准输出中。
阅读全文