将两个非递减单链表合并成一个有序的非递减单链表的c语言代码,利用头插法
时间: 2024-03-24 22:15:26 浏览: 139
单链表建立头插法(C语言源代码)
以下是将两个非递减单链表合并成一个有序的非递减单链表的c语言代码,利用头插法:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
// 头插法合并两个非递减单链表
ListNode* mergeLists(ListNode* l1, ListNode* l2) {
ListNode* dummy = (ListNode*)malloc(sizeof(ListNode)); // 虚拟头节点
dummy->next = NULL;
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(void) {
// 创建链表1:1 -> 3 -> 5 -> 7 -> 9
ListNode* l1 = (ListNode*)malloc(sizeof(ListNode));
l1->val = 1;
ListNode* l1_2 = (ListNode*)malloc(sizeof(ListNode));
l1_2->val = 3;
l1->next = l1_2;
ListNode* l1_3 = (ListNode*)malloc(sizeof(ListNode));
l1_3->val = 5;
l1_2->next = l1_3;
ListNode* l1_4 = (ListNode*)malloc(sizeof(ListNode));
l1_4->val = 7;
l1_3->next = l1_4;
ListNode* l1_5 = (ListNode*)malloc(sizeof(ListNode));
l1_5->val = 9;
l1_4->next = l1_5;
l1_5->next = NULL;
// 创建链表2:2 -> 4 -> 6 -> 8 -> 10
ListNode* l2 = (ListNode*)malloc(sizeof(ListNode));
l2->val = 2;
ListNode* l2_2 = (ListNode*)malloc(sizeof(ListNode));
l2_2->val = 4;
l2->next = l2_2;
ListNode* l2_3 = (ListNode*)malloc(sizeof(ListNode));
l2_3->val = 6;
l2_2->next = l2_3;
ListNode* l2_4 = (ListNode*)malloc(sizeof(ListNode));
l2_4->val = 8;
l2_3->next = l2_4;
ListNode* l2_5 = (ListNode*)malloc(sizeof(ListNode));
l2_5->val = 10;
l2_4->next = l2_5;
l2_5->next = NULL;
// 合并两个链表
ListNode* merged = mergeLists(l1, l2);
// 遍历输出合并后的链表
printf("合并后的链表:");
ListNode* node = merged;
while (node) {
printf("%d ", node->val);
node = node->next;
}
printf("\n");
// 释放链表节点的内存
node = merged;
while (node) {
ListNode* tmp = node;
node = node->next;
free(tmp);
}
node = l1;
while (node) {
ListNode* tmp = node;
node = node->next;
free(tmp);
}
node = l2;
while (node) {
ListNode* tmp = node;
node = node->next;
free(tmp);
}
return 0;
}
```
阅读全文