帮我写一个将两个带头节点的递增有序的单链表A和B合并到一个单链表C中,单链表C仍然递增有序的代码
时间: 2023-03-28 09:01:18 浏览: 91
设A和B是两个单链表,其表中元素递增有序
5星 · 资源好评率100%
以下是将两个带头节点的递增有序的单链表A和B合并到一个单链表C中,单链表C仍然递增有序的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkedList;
LinkedList createList(int n) {
LinkedList head = (LinkedList) malloc(sizeof(Node));
head->next = NULL;
LinkedList p = head;
for (int i = ; i < n; i++) {
LinkedList node = (LinkedList) malloc(sizeof(Node));
scanf("%d", &node->data);
node->next = NULL;
p->next = node;
p = node;
}
return head;
}
LinkedList mergeList(LinkedList A, LinkedList B) {
LinkedList C = (LinkedList) malloc(sizeof(Node));
C->next = NULL;
LinkedList p = C;
LinkedList pA = A->next, pB = B->next;
while (pA && pB) {
if (pA->data <= pB->data) {
p->next = pA;
pA = pA->next;
} else {
p->next = pB;
pB = pB->next;
}
p = p->next;
}
p->next = pA ? pA : pB;
return C;
}
void printList(LinkedList head) {
LinkedList p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
LinkedList A = createList(n);
LinkedList B = createList(m);
LinkedList C = mergeList(A, B);
printList(C);
return ;
}
```
希望能够帮到您!
阅读全文