线性表的顺序表示的代码
时间: 2024-05-31 12:08:31 浏览: 14
以下是线性表顺序表示的代码示例,采用 C 语言:
#define MAXSIZE 100 // 定义线性表的最大长度
typedef struct {
int data[MAXSIZE]; // 存储线性表元素的数组
int length; // 线性表当前长度
} SqList;
// 初始化线性表
void InitList(SqList *L) {
L->length = 0; // 初始长度为 0
}
// 获取线性表元素
int GetElem(SqList L, int i, int *e) {
if (i < 1 || i > L.length) {
return 0; // i 值不合法
}
*e = L.data[i - 1]; // 获取元素值存入 e 中
return 1; // 获取成功
}
// 插入线性表元素
int ListInsert(SqList *L, int i, int e) {
if (L->length == MAXSIZE) {
return 0; // 线性表已满,无法插入
}
if (i < 1 || i > L->length + 1) {
return 0; // 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 1; // 插入成功
}
// 删除线性表元素
int ListDelete(SqList *L, int i, int *e) {
if (L->length == 0) {
return 0; // 线性表为空,无法删除
}
if (i < 1 || i > L->length) {
return 0; // 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 1; // 删除成功
}
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)