用c语言编程已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。
时间: 2024-06-15 15:06:52 浏览: 147
以下是用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));
dummy->val = 0;
dummy->next = NULL;
// 创建一个指针用于遍历新链表
struct ListNode* curr = dummy;
// 遍历两个链表,比较节点的值,将较小的节点添加到新链表中
while (l1 != NULL && l2 != NULL) {
if (l1->val <= l2->val) {
curr->next = l1;
l1 = l1->next;
} else {
curr->next = l2;
l2 = l2->next;
}
curr = curr->next;
}
// 将剩余的节点添加到新链表中
if (l1 != NULL) {
curr->next = l1;
}
if (l2 != NULL) {
curr->next = l2;
}
// 返回新链表的头节点
return dummy->next;
}
// 测试函数
int main() {
// 创建链表1:1->2->4
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;
// 创建链表2:1->3->4
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* mergedList = mergeTwoLists(l1, l2);
// 输出合并后的链表
while (mergedList != NULL) {
printf("%d ", mergedList->val);
mergedList = mergedList->next;
}
return 0;
}
```
输出结果为:1 1 2 3 4 4
阅读全文