将两个非递减的有序链表合并为一个非递增的有序链表,用C++代码实现
时间: 2023-05-11 12:06:23 浏览: 213
以下是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 = NULL, *tail = NULL;
while (l1 && l2) {
if (l1->val <= l2->val) {
struct ListNode *node = l1;
l1 = l1->next;
node->next = NULL;
if (!head) {
head = tail = node;
} else {
node->next = head;
head = node;
}
} else {
struct ListNode *node = l2;
l2 = l2->next;
node->next = NULL;
if (!head) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
}
if (l1) {
if (!head) {
head = l1;
} else {
l1->next = head;
head = l1;
}
}
if (l2) {
if (!head) {
head = l2;
} else {
l2->next = head;
head = l2;
}
}
return head;
}
int main() {
struct ListNode *l1 = (struct ListNode *)malloc(sizeof(struct ListNode));
l1->val = 1;
l1->next = (struct ListNode *)malloc(sizeof(struct ListNode));
l1->next->val = 3;
l1->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
l1->next->next->val = 5;
l1->next->next->next = NULL;
struct ListNode *l2 = (struct ListNode *)malloc(sizeof(struct ListNode));
l2->val = 2;
l2->next = (struct ListNode *)malloc(sizeof(struct ListNode));
l2->next->val = 4;
l2->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
l2->next->next->val = 6;
l2->next->next->next = NULL;
struct ListNode *merged = mergeTwoLists(l1, l2);
while (merged) {
printf("%d ", merged->val);
merged = merged->next;
}
printf("\n");
return 0;
}
```
输出结果为:6 5 4 3 2 1,符合题目要求。
阅读全文