C语言单链表节点相加代码
时间: 2023-04-05 22:03:18 浏览: 87
c语言单链表程序
以下是 C 语言单链表节点相加的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *head = NULL, *tail = NULL;
int carry = 0;
while (l1 || l2 || carry) {
int sum = carry;
if (l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
}
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = sum % 10;
node->next = NULL;
carry = sum / 10;
if (!head) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
int main() {
struct ListNode *l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->val = 2;
l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->val = 4;
l1->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->next->val = 3;
l1->next->next->next = NULL;
struct ListNode *l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->val = 5;
l2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->val = 6;
l2->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->next->val = 4;
l2->next->next->next = NULL;
struct ListNode *result = addTwoNumbers(l1, l2);
while (result) {
printf("%d ", result->val);
result = result->next;
}
printf("\n");
return 0;
}
```
以上是 C 语言单链表节点相加的代码,希望能对你有所帮助。
阅读全文