/*----------sqlist.h----------*/
#ifndef SQLIST_H
#define SQLIST_H
//起始下标为 1
//最大下标为 SIZE
const int SIZE(10);
//此处修改默认表长大小
template <typename Type> class Sqlist{
public:
Sqlist(int maxsize=SIZE)
{
while(maxsize<1){
cout << "设置最大表长有误,请重新设置->: " ;
cin >> maxsize;
}
MaxSize=maxsize;
data=new Type[MaxSize+1]; // data[MaxSize] 为表满状态
last=0; //空表状态
}
~Sqlist()
{
delete [] data;
}
void Clear() //清空顺序表
{
last=0;
}
bool Empty() //判空
{
if(last==0)
return true;
else
return false;
}
status push_back(const Type &value) //压入(后插)
{
if(last==MaxSize){
cerr << "顺序表已满,操作失败! " << endl;
return 0;
}else {
data[last+1]=value;
last++;
return 1;
}
}
void Display() //显示
{
for(int i=1;i<=last;i++)
cout << data[i] << " ";
cout << endl;
}
Type GetElem(int i) //取元素
{
if(last==0){
cerr << "顺序表为空,操作失败! " ;
goto end;
}
if(i<1||i>last){
cerr << "下标越界,请检查->: ";
goto end;
}
return data[i];
end:cout << endl;
}
int Locate(const Type &value) //定位查找
{
if(last==0){
cerr << "顺序表为空,操作失败!" << endl;
return 0;
}
for(int i=1;i<=last;i++)
if(data[i]==value)
return i;
cerr << "顺序表中没有此元素:" << value << " !" <<endl;
return 0;
}
status Insert(int i,const Type &value) //插入操作
{
if(last==MaxSize){
cerr << "顺序表已满,操作失败!" << endl;
return 0;
}
if(i<1||i>last+1){
cerr << "插入位置有误,请检查: " << endl;
return 0;
}
for(int j=last;j>=i;j--)
data[j+1]=data[j];
data[i]=value;
last++;
}
status Delete(int i) //删除操作
{
if(last==0){
cerr << "顺序表为空,操作失败! " << endl;
return 0;
}
if(i<1||i>last){
cerr << "下标越界,请检查:" << endl;
return 0;
}
for(int j=i;j<last;j++)
data[j]=data[j+1];
last--;
return 1;
}
int length()
{
return last;
}
int size()
{
return last;
}
status Replace(int i,const Type &value) //替换
{
if(last==0 || i<1 || i > last){
cerr << "下标越界,操作失败。" << endl;
return 0;
}else{
data[i]=value;
return 1;
}
}
Type operator [](int i) //重载 []
{
if(i<1||i>last||last==0){
cerr << "下标越界,请检查! " << endl;
exit(0);
}else
return data[i];
}
private:
Type *data;
int last;
int MaxSize;
};
#endif
//本人正在自学数据结构,欢迎老师批评指正,谢谢关注