给我用c语言写一个由两个链表合成一个链表的代码
时间: 2024-05-05 17:20:18 浏览: 107
C语言合并两个带头节点升序排列链表
当然,我很乐意帮您解决这个问题。以下是一个用C语言编写的合并两个链表的代码:
```
#include <stdio.h>
#include <stdlib.h>
//链表节点的结构体
struct ListNode {
int val;
struct ListNode *next;
};
//合并两个链表的函数
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* cur = dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 ? l1 : l2;
return dummy->next;
}
//主函数
int main() {
//创建第一个链表
struct ListNode* l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->val = 1;
l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->val = 2;
l1->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->next->val = 4;
l1->next->next->next = NULL;
//创建第二个链表
struct ListNode* l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->val = 1;
l2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->val = 3;
l2->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->next->val = 4;
l2->next->next->next = NULL;
//合并两个链表
struct ListNode* merged = mergeTwoLists(l1, l2);
//输出结果
while (merged) {
printf("%d ", merged->val);
merged = merged->next;
}
return 0;
}
```
这个代码可以将两个链表合并成一个升序排列的新链表。
阅读全文