#include <iostream>
using namespace std;
#define MAX_SIZE 100
//typedef struct _Sqlist SqList;
typedef struct {
int *elems; //顺序表基地址
int length; //顺序表长度
int size; //顺序表总空间大小
}SqList;
//初始化表
bool initList(SqList &L)//构造一个空的顺寻表L
{
L.elems = new int[MAX_SIZE];//为顺序表分配MAX_SIZE个int元素的空间
if(!L.elems) return false; //存储分配失败
L.length = 0;
L.size = MAX_SIZE;
return true;
}
//打印元素
void listPrint(SqList &L){
cout<<"顺序表的存储空间size:"<<L.size<<",以保存元素个数 length:"<<L.length<<endl;
for(int i=0;i<=L.length-1;i++){
cout<<L.elems[i]<<" ";
}
cout<<endl;
}
//增加元素
bool listAppend(SqList &L,int e){
if(L.length == L.size){
cout<<"存储空间已满"<<endl;
return false;
}
cout<<"请输入要增加的元素个数"<<endl;
//L.length 表示长度,即已经有多少个元素
//假设已经有2个元素,因为下标从0开始,所以2正好代表下一个元素的下标,所以 L.elems[L.length] = e;
L.elems[L.length] = e;
L.length++;//表长加一
return true;
}
//表中插入数据
bool listInsert(SqList &L,int i,int e){
if( i < 0 || i>= L.length) return false; //i值不合法
if(L.length == L.size) return false; //空间已满
for(int j = L.length-1;j>=i;j--){
L.elems[j+1] = L.elems[j];//从最后一个位置开始后移,直到下标为i的元素
}
L.elems[i] = e;
L.length++;
return true;
}
bool listDelete(SqList &L,int i){
if(i<0 || i>=L.length) return false;
if(i == L.length-1){//删除最后一个元素
L.length--;
return true;
}
//length-1是最后一位
for(int j = i;j<L.length-1;j++){
L.elems[j] =L.elems[j+1];//后一位给前一位
}
L.length--;
return true;
}
void destoryList(SqList &L){
if(L.elems) delete []L.elems; //释放空间
L.length = 0;
L.size = 0;
}
int main(){
SqList list;
cout<<"顺序表初始化..."<<endl;
//1.初始化
if(initList(list)){
cout<<"顺序表初始化成功!"<<endl;
}
listPrint(list);
//2.添加元素
int count =0;
int e,i;
cout<<"请输入要添加的元素个数"<<endl;
cin>>count;
for(int i=0;i<count;i++){
cout<<"\n请输入要添加的元素e:";
cin>>e;
if(listAppend(list,e)){
cout<<"添加成功"<<endl;
}else{
cout<<"添加失败"<<endl;
}
}
//3.插入元素
cout<<"请输入要插入的下标和要插入的元素"<<endl;
cin>>i>>e;
if(listInsert(list,i,e)){
cout<<"插入成功!"<<endl;
}else{
cout<<"插入失败!"<<endl;
}
listPrint(list);
cout<<"请输入要删除元素的下标:"<<endl;
cin>>i;
if(listDelete(list,i)){
cout<<"删除成功!"<<endl;
}else{
cout<<"删除失败!"<<endl;
}
listPrint(list);
//3.销毁顺序表
destoryList(list);
system("pause");
return 0;
}
顺序表的算法实现
最新推荐文章于 2021-10-04 20:20:15 发布