顺序表的实现
#include<iostream>
#define MAXSIZE 15
#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) exit(OVERFLOW);
L.length=0;
return 1;
}
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;
}
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;
}
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 DestroyList(SqList &L){
// if(L.elem) delete [] L.elem;
//}
void ClearList(Sqlist &L){
L.length=0;
}
int main (){
Sqlist L;
int n,a,l,k,m;
InitList(L); //初始化
cout << "顺序表创建成功\n"<< "请输入顺序表长度n(1<=n<=15):";
cin >> n;
cout << "请依次输入n的值:";
for(int i=1;i<=n;i++){
cin >> a;
ListInsert(L,i,a);
}
cout << endl << "当前顺序表:\n";
for(int i=1;i<=L.length;i++){
GetElem(L,i,m);
cout << m << " ";
}
cout << endl;
cout << endl << "请输入插入位置与插入值:"; //插入
cin >> k >> l;
m=ListInsert(L,k,l);
if(!m){
cout << "插入失败!\n";
if(m==OVERFLOW)
cout << "初始分配空间已满!\n";
else
cout << "插入位置不合法!\n";
}
cout << endl << "当前顺序表:\n";
for(int i=1;i<=L.length;i++){
GetElem(L,i,m);
cout << m << " ";
}
cout << endl << endl;
cout << "请输入要删除元素的位置:"; //删除
cin >> l;
m=ListDelete(L,l);
if(!m)
cout << "删除位置不合法!\n";
cout << endl << "当前顺序表:\n";
for(int i=1;i<=L.length;i++){
GetElem(L,i,m);
cout << m << " ";
}
cout << endl << endl;
cout << "请输入要查找的值:"; //查找
cin >> k;
m=LocateElem(L,k);
if(!m)
cout <<"顺序表中没有这个值!\n";
else
cout << m << endl;
cout << endl << "当前顺序表:\n";
for(int i=1;i<=L.length;i++){
GetElem(L,i,m);
cout << m << " ";
}
cout << endl << endl;
cout << "请输入要取第几个值:"; // 取值
cin >> k;
GetElem(L,k,m);
if(m!=false)
cout << m << endl;
cout << endl << "当前顺序表:\n";
for(int i=1;i<=L.length;i++){
GetElem(L,i,m);
cout << m << " ";
}
cout << endl << endl;
// DestroyList(L);
cout << "清空顺序表\n";
ClearList(L); //清空顺序表
cout << endl << "当前顺序表:\n";
for(int i=1;i<=L.length;i++){
GetElem(L,i,m);
cout << m << " ";
}
cout << endl;
return 0;
}