//顺序表操作 建立 查找 插入 删除
#include <iostream
#define OK 1
#define ERROR 0
#define OVERFLOW -1 //判断是否溢出的时候要使用
#define MAXSIZE 100
using namespace std;
typedef int ElemType;
typedef int Status;
typedef struct{
int *elem;
int length;
}SqList;//顺序表存储结构类型为 SqList
//建立顺序表L并且初始化
Status InitList(SqList &L,int n){
L.elem= new ElemType[MAXSIZE]; //为顺序表分配一个大小为MAXSIZE的存储空间 动态分配
if(!L.elem) exit(OVERFLOW);//存储分配失败退出
cout<<“请输入顺序表中元素的个数:”;
cin>>n;
cout<<endl;
cout<<“请输入顺序表中元素:”;
for(int i=0;i<n;i++){
cin>>L.elem[i];
}
cout<<endl;
L.length=n;
return OK;
}
//输出顺序表中的元素
Status ExitList(SqList L){
cout<<“此时顺序表为:”;
for(int i=0;i<L.length;i++)
cout<<L.elem[i];
cout<<endl;
cout<<“顺序表长度为”<<L.length;
cout<<endl;
}
//获取顺序表中第i个数据元素的值
Status GetElem(SqList L,int i,ElemType &e){
cout<<endl;
cout<<“请输入您将要获取顺序表中第i位数据元素:\n”;
cin>>i;
cout<<endl;
if(i<1||i>L.length) return ERROR;//i是否合法
e=L.elem[i-1];
cout<<“顺序表中第”<<i<<“位数据元素的值为:”<<e<<endl;
return OK;
}
//查找指定元素值e
Status LocateElem(SqList L,ElemType e) {
cout<<endl;
cout<<“请输入您要查找的元素值:”;
cin>>e;
cout<<endl;
for(int i=0;i<L.length;i++)
if(L.elem[i]==e) return i+1;
return 0;
cout<<endl;
}
Status ListInsert(SqList &L,int i, ElemType e){
int j;
cout<<endl;
cout<<“请输入要插入的位置:”;
cin>>i;
cout<<endl;
cout<<“请输入要插入的元素:”;
cin>>e;
cout<<endl;
if((i<1)||(i>L.length+1)) return ERROR;
if(L.length >= MAXSIZE) return ERROR;
for(j=L.length-1; j>=i-1; j–) L.elem[j+1]=L.elem[j];
L.elem[i-1]=e;
L.length++;
return OK;
cout<<endl;
}
//顺序表删除
Status ListDelete(SqList &L,int i){
int j;
ElemType e;
cout<<endl;
cout<<“请输入想删除的位置i:”;
cin>>i;
cout<<endl;
if((i<1)||(i>L.length)) return ERROR;
e=L.elem[i-1];
cout<<“您要删除的值是”<<e<<endl;
/这里的删除并不是将顺序表中的值清空,而是顺序表的长度减1,
最后的值还保留着,但已经不在顺序表中了.因为是最后一个值,所以没有被覆盖./
for(j=i;j<=L.length-1;j++)
L.elem[j-1]=L.elem[j];
L.length–;
return OK;
}
int main()
{
int n,i;
ElemType e;
SqList L;
InitList(L,n);
ExitList(L);
GetElem(L,i,e);
cout<<“您要查找的值是顺序表中第”<<LocateElem(L,e)<<“位元素”;
ListInsert(L,i,e);
ExitList(L);
ListDelete(L,i);
ExitList(L);
return 0;
}