用C语言写两个非降序链表的并集,例如将链表1->2->3 和 2->3->5 并为 1->2->3->5,只能输出结果,不能修改两个链表的数据。
时间: 2023-05-28 11:05:51 浏览: 190
实现两个链表的合并(C语言)
```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 *)malloc(sizeof(Node));
Node *cur = dummy;
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 dummy->next;
}
int main() {
Node *l1 = (Node *)malloc(sizeof(Node));
l1->val = 1;
l1->next = (Node *)malloc(sizeof(Node));
l1->next->val = 2;
l1->next->next = (Node *)malloc(sizeof(Node));
l1->next->next->val = 3;
l1->next->next->next = NULL;
Node *l2 = (Node *)malloc(sizeof(Node));
l2->val = 2;
l2->next = (Node *)malloc(sizeof(Node));
l2->next->val = 3;
l2->next->next = (Node *)malloc(sizeof(Node));
l2->next->next->val = 5;
l2->next->next->next = NULL;
Node *result = merge(l1, l2);
while (result) {
printf("%d ", result->val);
result = result->next;
}
printf("\n");
return 0;
}
```
阅读全文