用c++写一个程序将两个升序链表合并成一个升序链表
时间: 2023-05-22 15:01:15 浏览: 118
C++实现合并两个排序的链表
5星 · 资源好评率100%
以下是用 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 *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 *l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *node1 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *node2 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *node3 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *node4 = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->val = 1;
l1->next = node1;
node1->val = 2;
node1->next = node2;
node2->val = 4;
node2->next = NULL;
l2->val = 1;
l2->next = node3;
node3->val = 3;
node3->next = node4;
node4->val = 4;
node4->next = NULL;
struct ListNode *result = mergeTwoLists(l1, l2);
while (result) {
printf("%d ", result->val);
result = result->next;
}
return 0;
}
```
这个程序将两个升序链表合并成一个升序链表,并输出结果。
阅读全文