将两个升序链表合并为一个新的升序链表并输出 c语言
时间: 2024-06-13 09:07:39 浏览: 114
c代码-将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
以下是将两个升序链表合并为一个新的升序链表的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 *head = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *cur = head;
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 head->next;
}
int main() {
// 创建链表1
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
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 *result = mergeTwoLists(l1, l2);
// 输出结果
while (result) {
printf("%d ", result->val);
result = result->next;
}
printf("\n");
return 0;
}
```
输出结果为:1 1 2 3 4 4
阅读全文