依据严蔚敏数据结构教材编写。
#include "iostream"
using namespace std;
#define MAXSIZE 100
typedef struct {
int *elem; //存储空间基地址
int length; //表长
}SqList;
bool InitList(SqList &L){ //初始化
L.elem = new int[MAXSIZE];
if(!L.elem)
return false;
L.length = 0;
return true;
}
bool CreatList(SqList &L){ //创建表
int a,i=0;
cin>>a;
while (a!=-1){
if(L.length == MAXSIZE){
cout<<"顺序表已满";
return false;
}
L.elem[i++] = a;
L.length++;
cin>>a;
}
return true;
}
bool GetElem(SqList L,int i,int &e){ //取值
if(i<1 || i>L.length+1) return false;
e = L.elem[i-1];
return true;
}
int LocateList(SqList L,int e){ //查找
for (int i = 0; i < L.length; i++)
if(L.elem[i] == e) return i+1;
return -1;
}
bool InsertList(SqList &L,int i,int e){ //插入
if(i<1 || i>L.length+1) return false;
if(L.length == MAXSIZE) return false;
for(int j = L.length-1;j>=i-1;j--)
L.elem[j+1] = L.elem[j];
L.elem[i-1] = e;
L.length++;
return true;
}
bool DeleteList(SqList &L,int i){ //删除
if(i<1 || i>L.length+1) return false;
for (int j = i; j <= L.length-1; j++)
L.elem[j-1] = L.elem[j];
L.length--;
return true;
}
void print(SqList L){ //输出表
cout<<"输出顺序表:"<<endl;
for (int i = 0; i < L.length; ++i)
cout<<L.elem[i]<<" ";
cout<<endl;
}
void DestoryList(SqList &L){ //销毁表
if(L.elem)
delete L.elem;
}
int main(){
SqList sqL;
int i,e;
cout<<"1.初始化"<<endl;
cout<<"2.创建"<<endl;
cout<<"3.取值"<<endl;
cout<<"4.查找"<<endl;
cout<<"5.插入"<<endl;
cout<<"6.删除"<<endl;
cout<<"7.输出"<<endl;
cout<<"8.销毁"<<endl;
cout<<"0.退出"<<endl;
int choose = -1;
while (choose != 0){
cout<<"请选择功能:";
cin>>choose;
switch (choose){
case 1: //初始化
cout<<"顺序表初始化中..."<<endl;
if(InitList(sqL))
cout<<"初始化成功!"<<endl;
else
cout<<"初始化失败"<<endl;
break;
case 2: //创建
cout<<"请输入整数,输入-1结束"<<endl;
if(CreatList(sqL))
cout<<"创建成功!"<<endl;
else
cout<<"创建失败"<<endl;
break;
case 3: //取值
cout<<"请输入所取元素位置i(整数):";
cin>>i;
if(GetElem(sqL,i,e))
cout<<"第"<<i<<"个元素是"<<e<<endl;
else
cout<<"取值失败"<<endl;
break;
case 4: //查找
cout<<"请输入要查找的整数e:";
cin>>e;
if(LocateList(sqL,e)==-1)
cout<<"表中没有该元素"<<endl;
else
cout<<e<<"在表中第"<<LocateList(sqL,e)<<"个"<<endl;
break;
case 5: //插入
cout<<"请输入要插入的位置i和插入元素e:";
cin>>i>>e;
if(InsertList(sqL,i,e))
cout<<"插入成功!"<<endl;
else
cout<<"插入失败"<<endl;
break;
case 6: //删除
cout<<"请输入要删除的位置i:";
cin>>i;
if(DeleteList(sqL,i))
cout<<"删除成功!"<<endl;
else
cout<<"删除失败"<<endl;
break;
case 7: //输出
print(sqL);
break;
case 8: //销毁
cout<<"顺序表销毁中..."<<endl;
DestoryList(sqL);
break;
}
}
return 0;
}
部分运行结果展示: