用C语言写出两个链表按大小顺序合并
时间: 2023-06-10 08:08:10 浏览: 109
c++ 如何合并两个有序链表
5星 · 资源好评率100%
下面是用C语言实现的两个链表按大小顺序合并的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode* next;
};
// 创建新的链表节点
struct ListNode* createNode(int val) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
// 合并两个有序链表
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
while (l1 && l2) {
if (l1->val < l2->val) {
if (head == NULL) {
head = tail = l1;
} else {
tail->next = l1;
tail = l1;
}
l1 = l1->next;
} else {
if (head == NULL) {
head = tail = l2;
} else {
tail->next = l2;
tail = l2;
}
l2 = l2->next;
}
}
if (l1) tail->next = l1;
if (l2) tail->next = l2;
return head;
}
int main() {
// 创建两个有序链表
struct ListNode* l1 = createNode(1);
l1->next = createNode(3);
l1->next->next = createNode(5);
struct ListNode* l2 = createNode(2);
l2->next = createNode(4);
l2->next->next = createNode(6);
l2->next->next->next = createNode(8);
// 合并两个有序链表
struct ListNode* mergedList = mergeTwoLists(l1, l2);
// 输出合并后的链表
while (mergedList) {
printf("%d ", mergedList->val);
mergedList = mergedList->next;
}
printf("\n");
return 0;
}
```
输出结果为:1 2 3 4 5 6 8
阅读全文