实现顺序表的基本操作c语言
时间: 2024-06-15 09:06:46 浏览: 20
顺序表是一种线性表的存储结构,可以使用数组来实现。下面是实现顺序表的基本操作的C语言代码:
1. 初始化顺序表:
```c
#define MAX_SIZE 100 // 定义顺序表的最大长度
typedef struct {
int data[MAX_SIZE]; // 用数组存储数据元素
int length; // 当前顺序表的长度
} SeqList;
void initList *list) {
list-> = 0; // 初始化长度为0
```
2.入元素:
```c
int insert(SeqList *list, int, int value) {
if (index < 0 || index > list->length || list->length == MAX_SIZE) {
return 0; 插入位置不合法或顺序表已满,插入失败
}
for (int i = list->length - 1; i >= index; i--) {
list->data[i + 1] = list->data[i]; // 将插入位置后的元素依次后移
}
list->data[index] = value; // 在插入位置插入新元素
list->length++; // 长度加1
return 1; // 插入成功
}
```
3. 删除元素:
```c
int remove(SeqList *list, int index) {
if (index < 0 || index >= list->length) {
return 0; // 删除位置不合法,删除失败
}
for (int i = index + 1; i < list->length; i++) {
list->data[i - 1] = list->data[i]; // 将删除位置后的元素依次前移
}
list->length--; // 长度减1
return 1; // 删除成功
}
```
4. 查找元素:
```c
int search(SeqList *list, int value) {
for (int i = 0; i < list->length; i++) {
if (list->data[i] == value) {
return i; // 找到元素,返回索引
}
}
return -1; // 未找到元素
}
```
5. 修改元素:
```c
int modify(SeqList *list, int index, int value) {
if (index < 0 || index >= list->length) {
return 0; // 修改位置不合法,修改失败
}
list->data[index] = value; // 修改元素的值
return 1; // 修改成功
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)