顺序表的相关操作
编译环境:Microsoft Visual C++2010学习版
参考教材:数据结构:C语言版/严蔚敏,李冬梅,吴伟民编
备注:本文留作作者自用,如有错误敬请指出
#include<iostream>
using namespace std;
#define MAX 10
int j;
typedef struct{
int *elem;
int len;
}sqlist;
bool InitList(sqlist &L){//初始化
L.elem=new int[MAX];
if(!L.elem) exit(-2);
L.len=0;
return true;
}
void DestroyList(sqlist &L){//销毁
if(L.elem)
delete []L.elem;
}
void ClearList(sqlist &L){//清空
L.len=0;
}
int ListLength(sqlist L){//求表长
return L.len;}
bool ListEmpty(sqlist L){//判断表是否为空
if(!L.len) return true;
else return false;
}
bool GetElem(sqlist L,int i,int &e){//取值
if(i<1||i>L.len) return false;
e=L.elem[i-1];
return true;
}
int LocateElem(sqlist L,int e){//查找
for(int i=0;i<L.len;++i)
if(L.elem[i]==e) return i+1;
return 0;
}
bool ListInsert(sqlist &L,int i,int e){//插入
if((i<1)||i>L.len+1) return false;
if(L.len==MAX) return false;
for(j=L.len-1;j>=i-1;--j)
L.elem[j+1]=L.elem[j];
L.elem[i-1]=e;
++L.len;
return true;
}
bool ListDelete(sqlist &L,int i){//删除
if(i<1||i>L.len) return false;
for(j=i;j<L.len;++j)
L.elem[j-1]=L.elem[j];
--L.len;
return true;
}
int main(){
sqlist L;
int e;
cout<<"---初始化--------"<<endl;
InitList(L);
cout<<"表长:"<<L.len<<endl;
cout<<"---求线性表的长度--------"<<endl;
for(int i=1;i<=9;++i){
L.elem[i-1]=i;
L.len++;}
cout<<"表长:"<<ListLength(L)<<endl;
cout<<"---判断表是否为空--------"<<endl;
cout<<"表是否为空:"<<(ListEmpty(L)?"是":"否")<<endl;
cout<<"---取值--------"<<endl;
GetElem(L,5,e);
cout<<"表中第五个元素是:"<<e<<endl;
cout<<"---查找--------"<<endl;
cout<<"表中第 "<<LocateElem(L,6)<<" 个元素是6"<<endl;
cout<<"---插入--------"<<endl;
ListInsert(L,6,66);
cout<<"表长:"<<L.len<<endl;
cout<<"---删除--------"<<endl;
ListDelete(L,9);
cout<<"表长:"<<L.len<<endl;
cout<<"---清空--------"<<endl;
ClearList(L);
cout<<"表长:"<<L.len<<endl;
cout<<"---销毁--------"<<endl;
DestroyList(L);
getchar();
return 0;
}