c语言数据结构代码实现将两个非递增有序链表合并为一个新的非递增有序链表并返回
时间: 2023-06-03 09:05:26 浏览: 124
下面是C语言的代码实现:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* merge(struct ListNode* l1, struct ListNode* l2) {
struct ListNode dummy;
struct ListNode* tail = &dummy;
while (l1 && l2) {
if (l1->val <= l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return dummy.next;
}
int main() {
struct ListNode *node1, *node2, *node3, *node4, *result;
// 构造链表1
node1 = (struct ListNode*)malloc(sizeof(struct ListNode));
node2 = (struct ListNode*)malloc(sizeof(struct ListNode));
node3 = (struct ListNode*)malloc(sizeof(struct ListNode));
node1->val = 5; node2->val = 3; node3->val = 1;
node1->next = node2; node2->next = node3; node3->next = NULL;
// 构造链表2
node2 = (struct ListNode*)malloc(sizeof(struct ListNode));
node3 = (struct ListNode*)malloc(sizeof(struct ListNode));
node4 = (struct ListNode*)malloc(sizeof(struct ListNode));
node2->val = 6; node3->val = 4; node4->val = 2;
node2->next = node3; node3->next = node4; node4->next = NULL;
// 合并两个链表
result = merge(node1, node2);
// 打印结果
while (result) {
printf("%d ", result->val);
result = result->next;
}
return 0;
}
输出结果:6 5 4 3 2 1
阅读全文