顺序表实现建立两个顺序表并将它们结合
时间: 2024-05-11 18:17:57 浏览: 15
要将两个顺序表结合,需要先确定两个顺序表的数据类型是否相同,若不同则需要进行类型转换。假设两个顺序表的数据类型相同,以下是一种实现方式:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int length;
} SeqList;
// 初始化顺序表
void InitList(SeqList *L) {
L->length = 0;
}
// 向顺序表中插入元素
int ListInsert(SeqList *L, int pos, int elem) {
if (pos < 1 || pos > L->length + 1 || L->length >= MAX_SIZE) {
return 0;
}
for (int i = L->length; i >= pos; i--) {
L->data[i] = L->data[i-1];
}
L->data[pos-1] = elem;
L->length++;
return 1;
}
// 输出顺序表中的元素
void PrintList(SeqList L) {
for (int i = 0; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
}
// 将两个顺序表结合
SeqList MergeList(SeqList L1, SeqList L2) {
SeqList L;
InitList(&L);
int i = 0, j = 0, k = 0;
while (i < L1.length && j < L2.length) {
if (L1.data[i] < L2.data[j]) {
L.data[k++] = L1.data[i++];
} else {
L.data[k++] = L2.data[j++];
}
}
while (i < L1.length) {
L.data[k++] = L1.data[i++];
}
while (j < L2.length) {
L.data[k++] = L2.data[j++];
}
L.length = k;
return L;
}
int main() {
SeqList L1, L2, L;
InitList(&L1);
InitList(&L2);
ListInsert(&L1, 1, 1);
ListInsert(&L1, 2, 3);
ListInsert(&L1, 3, 5);
ListInsert(&L2, 1, 2);
ListInsert(&L2, 2, 4);
ListInsert(&L2, 3, 6);
L = MergeList(L1, L2);
PrintList(L);
return 0;
}
```
在这个实现中,我们先定义了一个 SeqList 结构体来表示顺序表,包含一个 int 数组 data 和一个 int 变量 length,前者用来存储元素,后者表示当前顺序表的长度。InitList 函数用来初始化顺序表,ListInsert 函数用来向顺序表中插入元素,PrintList 函数用来输出顺序表中的元素。MergeList 函数用来将两个顺序表结合,具体实现是定义一个新的顺序表 L,然后使用双指针法将 L1 和 L2 中的元素按照从小到大的顺序合并到 L 中。最后输出 L 中的元素即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)