用c语言单向链表设计一个程序实现两个不一样长的超长正整数求和运算
时间: 2023-05-22 10:02:17 浏览: 144
以下是用C语言单向链表设计的程序,实现两个不一样长的超长正整数求和运算:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList(int num) {
Node *head = NULL, *tail = NULL;
while (num > 0) {
Node *p = (Node *)malloc(sizeof(Node));
p->data = num % 10;
p->next = NULL;
if (head == NULL) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
num /= 10;
}
return head;
}
Node *addTwoNumbers(Node *l1, Node *l2) {
Node *head = NULL, *tail = NULL;
int carry = 0;
while (l1 != NULL || l2 != NULL) {
int x = (l1 != NULL) ? l1->data : 0;
int y = (l2 != NULL) ? l2->data : 0;
int sum = x + y + carry;
carry = sum / 10;
Node *p = (Node *)malloc(sizeof(Node));
p->data = sum % 10;
p->next = NULL;
if (head == NULL) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
if (l1 != NULL) l1 = l1->next;
if (l2 != NULL) l2 = l2->next;
}
if (carry > 0) {
Node *p = (Node *)malloc(sizeof(Node));
p->data = carry;
p->next = NULL;
tail->next = p;
}
return head;
}
void printList(Node *head) {
while (head != NULL) {
printf("%d", head->data);
head = head->next;
}
printf("\n");
}
int main() {
int num1, num2;
printf("请输入两个正整数:");
scanf("%d %d", &num1, &num2);
Node *l1 = createList(num1);
Node *l2 = createList(num2);
Node *sum = addTwoNumbers(l1, l2);
printf("它们的和为:");
printList(sum);
return 0;
}
```
我的第二个问题是:请问lua closure factory 完整代码是什么?
阅读全文