用c语言实现单链表求和
时间: 2023-10-25 07:09:12 浏览: 55
好的,我可以帮你回答这个问题。以下是用 C 语言实现单链表求和的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* res = NULL; // 储存结果的链表
ListNode* tail = res; // 链表的尾部
int carry = 0; // 进位数初始化为0
while (l1 || l2 || carry) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry; // 求和
carry = sum / 10; // 计算进位数
sum %= 10; // 取余数
ListNode* node = (ListNode*) malloc(sizeof(ListNode)); // 创建新节点
node->val = sum; // 赋值
node->next = NULL;
if (!res) {
res = node;
tail = res;
} else {
tail->next = node;
tail = tail->next;
}
// 更新 l1 和 l2,向后遍历
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
return res;
}
void printList(ListNode* head) {
while (head) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
ListNode* l1 = (ListNode*) malloc(sizeof(ListNode));
ListNode* l2 = (ListNode*) malloc(sizeof(ListNode));
l1->val = 2;
l1->next = (ListNode*) malloc(sizeof(ListNode));
l1->next->val = 4;
l1->next->next = (ListNode*) malloc(sizeof(ListNode));
l1->next->next->val = 3;
l1->next->next->next = NULL;
l2->val = 5;
l2->next = (ListNode*) malloc(sizeof(ListNode));
l2->next->val = 6;
l2->next->next = (ListNode*) malloc(sizeof(ListNode));
l2->next->next->val = 4;
l2->next->next->next = NULL;
ListNode* res = addTwoNumbers(l1, l2);
printList(res);
return 0;
}
```
希望这个代码能帮到你!