#include <stdio.h>
#include <stdlib.h>
#define M 100 // 线性表的最大容量
typedef int ElemType; // 定义元素类型
// 顺序线性表的结构体定义
typedef struct {
ElemType *elem; // 存放元素的动态数组
int length; // 线性表中当前元素的个数
} Sqlist;
// 初始化线性表
void InitList(Sqlist &L) {
L.elem = new ElemType[M];
if (!L.elem) {
exit(0); // 分配内存失败,退出程序
}
L.length = 0; // 初始化长度为0
}
// 销毁线性表
void DestroyList(Sqlist &L) {
free(L.elem); // 释放内存
L.length = 0; // 将长度设置为0
}
// 插入元素
int Insert(Sqlist &L, int i, ElemType e) {
if (i < 1 || i > L.length + 1) {
return 0; // 插入位置不合法
}
if (L.length >= M) {
return 0; // 线性表已满
}
for (int j = L.length; j >= i; j--) {
L.elem[j] = L.elem[j - 1]; // 将元素后移
}
L.elem[i - 1] = e; // 插入元素
L.length++; // 长度加1
return 1;
}
// 删除元素
int Delete(Sqlist &L, int i, ElemType *e) {
if (i < 1 || i > L.length) {
return 0; // 删除位置不合法
}
*e = L.elem[i - 1]; // 获取被删除的元素
for (int j = i; j < L.length; j++) {
L.elem[j - 1] = L.elem[j]; // 将元素前移
}
L.length--; // 长度减1
return 1;
}
// 获取元素
int GetElem(Sqlist L, int i, ElemType *e) {
if (i < 1 || i > L.length) {
return 0; // 获取位置不合法
}
*e = L.elem[i - 1]; // 获取元素
return 1;
}
// 查找元素
int LocateElem(Sqlist L, ElemType e) {
for (int i = 0; i < L.length; i++) {
if (L.elem[i] == e) {
return i + 1; // 查找成功,返回位置
}
}
return 0; // 查找失败,返回0
}
// 判断线性表是否为空
int ListEmpty(Sqlist L) {
return L.length == 0;
}
// 获取线性表的长度
int ListLength(Sqlist L) {
return L.length;
}
int main() {
Sqlist L;
ElemType e;
InitList(L);
Insert(L, 1, 1);
Insert(L, 2, 2);
Insert(L, 3, 3);
Delete(L, 2, &e);
printf("删除的元素:%d\n", e);
GetElem(L, 2, &e);
printf("第2个元素:%d\n", e);
printf("查找元素3的位置:%d\n", LocateElem(L, 3));
printf("线性表是否为空:%d\n", ListEmpty(L));
printf("线性表的长度:%d\n", ListLength(L));
DestroyList(L); // 销毁线性表
return 0;
}