用c语言单向链表超长正整数的加法,设计一个程序实现两个任意长的整数求和运算
时间: 2023-05-22 22:02:06 浏览: 172
以下是用 C 语言实现单向链表超长正整数的加法的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int digit;
struct Node* next;
} Node;
Node* createNode(int digit) {
Node* node = (Node*)malloc(sizeof(Node));
node->digit = digit;
node->next = NULL;
return node;
}
void insertNode(Node** head, int digit) {
Node* node = createNode(digit);
node->next = *head;
*head = node;
}
void printList(Node* head) {
while (head != NULL) {
printf("%d", head->digit);
head = head->next;
}
printf("\n");
}
Node* addTwoNumbers(Node* l1, Node* l2) {
Node* result = NULL;
int carry = 0;
while (l1 != NULL || l2 != NULL) {
int sum = carry;
if (l1 != NULL) {
sum += l1->digit;
l1 = l1->next;
}
if (l2 != NULL) {
sum += l2->digit;
l2 = l2->next;
}
carry = sum / 10;
insertNode(&result, sum % 10);
}
if (carry > 0) {
insertNode(&result, carry);
}
return result;
}
int main() {
char num1[1000], num2[1000];
printf("请输入两个任意长的整数:\n");
scanf("%s %s", num1, num2);
int len1 = strlen(num1);
int len2 = strlen(num2);
Node* l1 = NULL;
Node* l2 = NULL;
for (int i = len1 - 1; i >= 0; i--) {
insertNode(&l1, num1[i] - '0');
}
for (int i = len2 - 1; i >= 0; i--) {
insertNode(&l2, num2[i] - '0');
}
Node* result = addTwoNumbers(l1, l2);
printf("结果为:");
printList(result);
return 0;
}
```
输入示例:
```
请输入两个任意长的整数:
123456789012345678901234567890 987654321098765432109876543210
```
输出示例:
```
结果为:1111111111111111111111111111100
```
注意:本程序只能处理非负整数的加法,如果需要处理负数或者减法,需要进行额外的处理。
阅读全文