用c/c++写一个程序将两个升序链表合并成一个升序链表
时间: 2023-05-22 13:01:14 浏览: 101
好的,这是一个比较常见的链表问题,可以使用递归或迭代的方式来解决。以下是一个使用迭代的示例代码:
```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 = malloc(sizeof(struct ListNode));
l1->val = 1;
l1->next = malloc(sizeof(struct ListNode));
l1->next->val = 2;
l1->next->next = malloc(sizeof(struct ListNode));
l1->next->next->val = 4;
l1->next->next->next = NULL;
struct ListNode *l2 = malloc(sizeof(struct ListNode));
l2->val = 1;
l2->next = malloc(sizeof(struct ListNode));
l2->next->val = 3;
l2->next->next = malloc(sizeof(struct ListNode));
l2->next->next->val = 4;
l2->next->next->next = NULL;
struct ListNode *merged = mergeTwoLists(l1, l2);
while (merged) {
printf("%d ", merged->val);
merged = merged->next;
}
return 0;
}
```
这个程序将两个升序链表合并成一个升序链表,并输出结果:1 1 2 3 4 4。
阅读全文