线性表的顺序存储结构实现代码
时间: 2024-06-12 16:10:08 浏览: 20
线性表的顺序存储结构可以使用数组来实现,以下是一个简单的示例代码:
```
#define MAXSIZE 100 // 定义线性表的最大长度
typedef struct {
int data[MAXSIZE]; // 存储元素的数组
int length; // 线性表的当前长度
} SqList;
// 初始化线性表
void InitList(SqList *L) {
L->length = 0;
}
// 插入元素
bool ListInsert(SqList *L, int i, int e) {
if (i < 1 || i > L->length + 1 || L->length == MAXSIZE) {
return false; // i值不合法或线性表已满
}
for (int j = L->length; j >= i; j--) {
L->data[j] = L->data[j-1]; // 将第i个元素及之后的元素后移
}
L->data[i-1] = e; // 在位置i处插入元素e
L->length++; // 线性表长度加1
return true;
}
// 删除元素
bool ListDelete(SqList *L, int i, int *e) {
if (i < 1 || i > L->length) {
return false; // i值不合法
}
*e = L->data[i-1]; // 将被删除的元素赋值给e
for (int j = i; j < L->length; j++) {
L->data[j-1] = L->data[j]; // 将第i个元素之后的元素前移
}
L->length--; // 线性表长度减1
return true;
}
// 查找元素
int LocateElem(SqList L, int e) {
for (int i = 0; i < L.length; i++) {
if (L.data[i] == e) {
return i+1; // 返回元素在线性表中的位置
}
}
return 0; // 没有找到元素e
}
```
相关推荐
![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)