2、现有两个递减的有序链表(带头结点的单链表),分别为La和Lb,需要合并成一个新的链表Lc,请你完成链表合并函数。给出C语言代码
时间: 2023-05-30 12:06:22 浏览: 86
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建链表
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
// 合并两个有序链表
Node* mergeLists(Node* La, Node* Lb) {
Node* Lc = createList();
Node* pa = La->next;
Node* pb = Lb->next;
Node* pc = Lc;
while (pa != NULL && pb != NULL) {
if (pa->data > pb->data) {
pc->next = pb;
pb = pb->next;
} else {
pc->next = pa;
pa = pa->next;
}
pc = pc->next;
}
pc->next = pa ? pa : pb;
free(La);
free(Lb);
return Lc;
}
// 输出链表
void printList(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node* La = createList();
Node* Lb = createList();
int n, m, x;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
Node* p = (Node*)malloc(sizeof(Node));
p->data = x;
p->next = La->next;
La->next = p;
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &x);
Node* p = (Node*)malloc(sizeof(Node));
p->data = x;
p->next = Lb->next;
Lb->next = p;
}
Node* Lc = mergeLists(La, Lb);
printList(Lc);
return 0;
}
```
阅读全文