用c++语言创建三个线性表A,B,C,将A,B中元素一隔存入C中,线性表A,B,C均以单链表作为存储结构输出C,
时间: 2023-05-14 22:06:34 浏览: 112
以下是用 C 语言创建三个线性表 A,B,C,将 A,B 中元素一隔存入 C 中,线性表 A,B,C 均以单链表作为存储结构输出 C 的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList(int* arr, int len) {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
Node* tail = head;
for (int i = 0; i < len; i++) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = arr[i];
node->next = NULL;
tail->next = node;
tail = node;
}
return head;
}
void printList(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
Node* mergeList(Node* A, Node* B) {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
Node* tail = head;
Node* p = A->next;
Node* q = B->next;
while (p != NULL && q != NULL) {
Node* node = (Node*)malloc(sizeof(Node));
node->next = NULL;
if (p->data < q->data) {
node->data = p->data;
p = p->next;
} else {
node->data = q->data;
q = q->next;
}
tail->next = node;
tail = node;
}
while (p != NULL) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = p->data;
node->next = NULL;
tail->next = node;
tail = node;
p = p->next;
}
while (q != NULL) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = q->data;
node->next = NULL;
tail->next = node;
tail = node;
q = q->next;
}
return head;
}
int main() {
int arrA[] = {1, 3, 5, 7, 9};
int arrB[] = {2, 4, 6, 8, 10};
Node* A = createList(arrA, 5);
Node* B = createList(arrB, 5);
Node* C = mergeList(A, B);
printf("List A: ");
printList(A);
printf("List B: ");
printList(B);
printf("List C: ");
printList(C);
return 0;
}
```
输出结果为:
```
List A: 1 3 5 7 9
List B: 2 4 6 8 10
List C: 1 2 3 4 5 6 7 8 9 10
```
阅读全文