顺序表,是数据结构中按顺序方式存储的线性表,又称向量。具有方便检索的特点。以下,是笔者学习是基于C++实现的顺序表代码,贴上来当网页笔记用。
#include <iostream>
using namespace std;
template <class T>
class List{
void clear();//释放顺序表
bool isEmpty();//判断顺序表是否为空
bool append(const T value);//在顺序表后添加value值
bool insert(const int p,const T value);//在p位置插入value值
bool del(const int p);//删除在p位置的值
bool getValue(const int p,T& value);//将p位置的值赋予value
bool setValue(const int p,const T value);//将p位置的值设置为value
bool getPos(int &p,const T value);//将值为value的位置赋予p
};
template <class T>
class arrList:public List<T> {
private:
T *aList; //存储顺序表的实例
int maxSize;//顺序表的最大值
int curLen;//顺序表的实际长度
int position;//顺序表的当前处理位置
public:
arrList(const int size){//初始化顺序表
maxSize=size;
aList=new T[maxSize];
curLen=position=0;
}
~arrList(){//消除表实例
delete [] aList;
}
void clear(){//清空顺序表,成为空表
delete [] aList;
curLen=position=0;
aList=new T[maxSize];
}
bool isEmpty(){
/*判断顺序表是否为空
若curLen为空,即当前实际长度为空,即为空表
*/
if(curLen==0){
return true;
}else{
return false;
}
}
int length(){
//返回顺序表的当前长度
return curLen;
}
bool append(const T value){
/*
在顺序表末插入value
实际长度+1
*/
aList[curLen]=value;
curLen++;
}
bool insert(const int p,const T value){
int i;
if(curLen>=maxSize){
/*判断顺序表是否已满*/
cout<<"The list is overflow"<<endl;
return false;
}
if(p<0||p>curLen){
/*判断请求合理性*/
cout<<"Insertion point is illegal"<<endl;
return false;
}
for(i=curLen;i>p;i--){
/*将p后的数据后移*/
aList[i]=aList[i-1];
}
/*将值置于p,curLen位置加1*/
aList[p]=value;
curLen++;
return true;
}
bool del(const int p){
int i;
/*判断当前表是否为空,为空不删除*/
if(curLen<=0){
cout<<"No element to del"<<endl;
return false;
}
/*判断请求合理性*/
if(p<0||p>curLen-1){
cout<<"deletion is illegal"<<endl;
return false;
}
/*将位置p后的值前移,覆盖*/
for(i=p;i<curLen-1;i++){
aList[i]=aList[i+1];
}
curLen--;
return true;
}
bool getValue(const int p,T& value){
//判断请求合理性
if(p<0||p>curLen-1){
cout<<"No such element"<<endl;
return false;
}
value=aList[p];
}
bool setValue(const int p,const T value){
//判断请求合理性
if(p<0||p>curLen-1){
cout<<"No such element"<<endl;
return false;
}
aList[p]=value;
}
bool getPos(int &p,const T value){
int i;
for(i=0;i<curLen;i++){
if(value==aList[i]){
p=i;
return true;
}
return false;
}
}
};