//简单顺序表的实现
#include<iostream>
#define MAXSIZE 10
#define OVERFLOW -2
using namespace std;
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;
}
int ListInsert(Sqlist &L,int i,int e)
{
if(i<1||i>L.length+1)
return false;
if(L.length==MAXSIZE)
return OVERFLOW;
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 GetElem(Sqlist L,int i,int &e)
{
if(i<1||i>L.length)
{
cout << "访问位置不合法!\n";
return false;
}
e=L.elem[i-1];
return true;
}
//删除第i个元素
bool ListDelete(Sqlist &L,int i)
{
if(i<1||i>L.length)
return false;
for(int j=i;j<L.length;j++)
L.elem[j-1]=L.elem[j];
L.length--;
return true;
}
//定位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;
}
void ClearList(Sqlist &L)
{
L.length=0;
}
int main()
{
int n;
Sqlist L;
cout << "简单顺序表的基本操作:\n"
<< "1、建立顺序表并存储5个数\n"
<< "2、插入\n"
<< "3、删除\n"
<< "4、查找\n"
<< "5、取值\n"
<< "6、清空\n"
<< "0、退出系统\n";
while(1)
{
int k,l,m;
cout <<"输入序号,进行相关操作:";
cin >> n;
switch(n)
{
case 1:
if(InitList(L))
{
cout << "顺序表创建成功\n";
for(int i=1;i<=5;i++)
ListInsert(L,i,i);
}
else
{
cout << "顺序表创建失败,自动退出程序!\n";
break;
}
break;
case 2:
cout << "请输入插入位置与插入值:";
cin >> k >> l;
m=ListInsert(L,k,l);
if(!m)
{
cout << "插入失败!\n";
if(m==OVERFLOW)
cout << "初始分配空间已满!\n";
else
cout << "插入位置不合法!\n";
}
break;
case 3:
cout << "请输入要删除元素的位置:";
cin >> l;
m=ListDelete(L,l);
if(!m)
cout << "删除位置不合法!\n";
break;
case 4:
cout << "请输入要查找的值:";
cin >> k;
m=LocateElem(L,k);
if(!m)
cout <<"顺序表中没有这个值!\n";
else
cout << m << endl;
break;
case 5:
cout << "请输入要取第几个值:";
cin >> k;
GetElem(L,k,m);
if(m!=false)
cout << m << endl;
break;
case 6:
ClearList(L);
break;
case 0:
exit(0);
}
cout << "------------------------------------------------\n";
cout << "当前顺序表:\n";
for(int i=1;i<=L.length;i++)
{
int m;
GetElem(L,i,m);
cout << m << " ";
}
cout << "\n------------------------------------------------\n";
}
return 0;
}
运行结果如下: