写一个集合插入,删除,打印和寻找的顺序表
时间: 2023-05-26 09:04:39 浏览: 60
顺序表是一种线性表的存储方式,插入和删除操作需要移动数据,时间复杂度为O(n)。以下是一个基于顺序表的集合实现,包含插入,删除,打印和寻找操作:
1. 定义一个包含数据区和长度信息的结构体:
```
typedef struct {
int data[MAXSIZE]; // 存储数据的数组
int length; // 集合的长度
} SqList;
```
2. 插入操作,在顺序表的最后插入元素:
```
void insert(SqList* L, int x) {
if (L->length == MAXSIZE) { // 判断集合是否已满
printf("集合已满,无法插入\n");
return;
}
L->data[L->length++] = x; // 在顺序表的末尾插入元素,并更新集合长度
}
```
3. 删除操作,删除顺序表中第一次出现的指定元素:
```
void remove(SqList* L, int x) {
int i, j;
for (i = 0; i < L->length; i++) { // 遍历集合
if (L->data[i] == x) { // 找到需要删除的元素
for (j = i; j < L->length - 1; j++) { // 移动数据
L->data[j] = L->data[j+1];
}
L->length--; // 减少集合长度
return;
}
}
printf("集合中未找到元素 %d\n", x);
}
```
4. 打印操作,输出集合中所有元素:
```
void print(SqList L) {
int i;
printf("集合中的所有元素为:");
for (i = 0; i < L.length; i++) { // 遍历集合
printf("%d ", L.data[i]); // 输出元素
}
printf("\n");
}
```
5. 寻找操作,查找顺序表中第一个与指定元素相同的元素,并返回其下标:
```
int find(SqList L, int x) {
int i;
for (i = 0; i < L.length; i++) { // 遍历集合
if (L.data[i] == x) { // 找到元素
return i;
}
}
return -1; // 未找到元素
}
```
以上就是基于顺序表实现的集合插入,删除,打印和寻找操作的示例代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)