#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 108
typedef int Status;
typedef int elemtype;
typedef struct{
elemtype *elem;
int length;
}SqList;
Status InitList_Sq(SqList &L)//构造一个空的顺序表
{
L.elem=new elemtype[MAXSIZE];
if(!L.elem) exit(OVERFLOW);
L.length=0;
return OK;
}
int LocateElem_Sq(SqList L,elemtype e)//顺序表的查找
{ int i;
for(i=0;i<L.length;i++)
{
if(L.elem[i]==e) return i+1;
}
return 0;
}
Status ListInsert_Sq(SqList &L,int i,elemtype e)//顺序表的插入
{ int j;
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;
}
Status ListDelete_Sq(SqList &L,int i,elemtype &e)//顺序表的删除 ,记得是&e
{
if((i<1)||(i>L.length)) return ERROR;
e=L.elem[i-1];
for(int j=i;j<=L.length-1;j++)
{
L.elem[j-1]=L.elem[j];
}
L.length--;
return OK;
}
void DestroyList(SqList &L)
{
if(L.elem) delete[]L.elem;
}
void ClearList(SqList &L)
{
L.length=0;
}
int main()
{ int choose,n,i,e,temp,a,b,c,d;
SqList la;
cout<<"1.建立线性表\n";
cout<<"2.输入线性表数据\n";
cout<<"3.按位置查找数据\n";
cout<<"4.插入数据\n";
cout<<"5.删除数据\n";
cout<<"6.输出全部数据\n";
cout<<"7.清除所有数据\n";
cout<<"0.退出!\n";
choose=-1;
while(choose!=0)
{
cout<<"请选择:";
cin>>choose;
switch(choose)
{
case 1:if(InitList_Sq(la))
cout<<"线性表建立成功!\n";
else
cout<<"线性表建立失败!\n";
break;
case 2:cout<<"请输入要输入的数据个数:";
cin>>n;
cout<<"请输入数据:";
for(i=0;i<n;i++)
cin>>la.elem[i];
la.length=n;
cout<<endl;
break;
case 3:cout<<"请输入要查找的数据:";
cin>>e;
temp=LocateElem_Sq(la,e);
if(temp!=0)
cout<<e<<"位于第"<<temp<<"个位置"<<endl;
else
cout<<"该数据不存在,查找不到!\n";
break;
case 4:cout<<"输入要插入的数据的位置和数据本身:\n";
cin>>a>>b;
if(ListInsert_Sq(la,a,b))
cout<<"插入成功!\n";
else
cout<<"插入位置不合法,插入失败!\n";
break;
case 5:cout<<"请出入要删除的数据的位置:\n";
cin>>c;
if(ListDelete_Sq(la,c,d))
cout<<"删除数据"<<d<<"成功!\n";
else
cout<<"删除位置不合法,删除失败!"<<endl;
break;
case 6:cout<<"输出所有数据:";
for(i=0;i<la.length;i++)
{
cout<<la.elem[i]<<" ";
}
cout<<endl;
break;
case 7:ClearList(la);
cout<<"清除成功!\n";
}
}
DestroyList(la);
return 0;
}