顺序表的构建、插入、删除、查找、反转实现C++
时间: 2023-09-30 18:07:01 浏览: 47
以下是顺序表的构建、插入、删除、查找、反转的C语言实现:
1. 顺序表的构建
typedef struct{
int *elem; //存储空间基址
int length; //当前长度
int size; //分配的存储容量
}SqList;
//初始化顺序表
void InitList(SqList &L, int size){
L.elem = (int*)malloc(size*sizeof(int)); //动态分配存储空间
if(!L.elem) exit(0); //分配失败
L.length = 0; //空表长度为0
L.size = size; //存储容量为size
}
2. 顺序表的插入
//在顺序表L的第i个位置插入元素e
bool ListInsert(SqList &L, int i, int e){
if(i<1 || i>L.length+1) return false; //插入位置不合法
if(L.length >= L.size) return false; //存储空间已满
for(int j=L.length; j>=i; j--){
L.elem[j] = L.elem[j-1]; //将第i个位置及以后的元素后移
}
L.elem[i-1] = e; //插入元素e
L.length++; //表长加1
return true;
}
3. 顺序表的删除
//删除顺序表L的第i个位置的元素,并用e返回其值
bool ListDelete(SqList &L, int i, int &e){
if(i<1 || i>L.length) return false; //删除位置不合法
e = L.elem[i-1]; //保存待删除元素
for(int j=i; j<L.length; j++){
L.elem[j-1] = L.elem[j]; //将第i个位置之后的元素前移
}
L.length--; //表长减1
return true;
}
4. 顺序表的查找
//在顺序表L中查找值为e的元素,并返回其位置
int LocateElem(SqList L, int e){
for(int i=0; i<L.length; i++){
if(L.elem[i] == e) return i+1; //找到元素,返回位置
}
return 0; //未找到元素,返回0
}
5. 顺序表的反转
//将顺序表L中的元素顺序反转
void ListReverse(SqList &L){
int temp;
for(int i=0; i<L.length/2; i++){ //只需遍历一半的元素
temp = L.elem[i];
L.elem[i] = L.elem[L.length-i-1];
L.elem[L.length-i-1] = temp;
}
}