用c语言写一个非递增的两个单链表的合并
时间: 2023-04-05 19:01:56 浏览: 85
可以使用以下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node* next;
} Node;
Node* merge(Node* l1, Node* l2) {
Node dummy;
Node* 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() {
Node* l1 = (Node*)malloc(sizeof(Node));
l1->val = 3;
l1->next = (Node*)malloc(sizeof(Node));
l1->next->val = 2;
l1->next->next = (Node*)malloc(sizeof(Node));
l1->next->next->val = 1;
l1->next->next->next = NULL;
Node* l2 = (Node*)malloc(sizeof(Node));
l2->val = 4;
l2->next = (Node*)malloc(sizeof(Node));
l2->next->val = 2;
l2->next->next = (Node*)malloc(sizeof(Node));
l2->next->next->val = 1;
l2->next->next->next = NULL;
Node* merged = merge(l1, l2);
while (merged) {
printf("%d ", merged->val);
merged = merged->next;
}
printf("\n");
return 0;
}
```
这个程序会创建两个单链表 `l1` 和 `l2`,然后调用 `merge` 函数将它们合并成一个非递增的单链表,并输出结果。
阅读全文