写一段代码实现两个超大整数的相加,使用c语言和线性链表实现
时间: 2023-04-09 22:03:48 浏览: 125
以下是使用C语言和线性链表实现两个超大整数相加的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createNode(int data) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
Node *addTwoNumbers(Node *l1, Node *l2) {
Node *result = NULL;
Node *tail = NULL;
int carry = 0;
while (l1 || l2 || carry) {
int sum = carry;
if (l1) {
sum += l1->data;
l1 = l1->next;
}
if (l2) {
sum += l2->data;
l2 = l2->next;
}
carry = sum / 10;
sum = sum % 10;
Node *newNode = createNode(sum);
if (!result) {
result = newNode;
tail = result;
} else {
tail->next = newNode;
tail = tail->next;
}
}
return result;
}
void printList(Node *head) {
while (head) {
printf("%d", head->data);
head = head->next;
}
printf("\n");
}
int main() {
Node *l1 = createNode(9);
l1->next = createNode(9);
l1->next->next = createNode(9);
Node *l2 = createNode(1);
printf("l1: ");
printList(l1);
printf("l2: ");
printList(l2);
Node *result = addTwoNumbers(l1, l2);
printf("result: ");
printList(result);
return 0;
}
```
这段代码可以处理超过int类型范围的整数相加,使用了链表来存储每一位数字,从低位到高位依次相加,处理进位,最后得到结果。
阅读全文