线性表基本操作模板
const int MaxSize=100;
template<class DataType>
class SeqList
{
public:
SeqList(){length=0;} //无参构造函数,建立一个空的顺序表
SeqList(DataType a[],int n); //有参构造函数,建立一个长度为n的顺序表
~SeqList(){} //析构函数为空
int Length(){return length;} //求线性表的长度
DateType Get(int i); //按位查找,在线性表中查找第i个元素
int Locate(DataType x); //按值查找,在线性表中查找值为x的元素序号
void Insert(int i,DataType x); //插入操作,在线性表中第i个位置插入值为x的元素
DateType Delete(int i); //删除操作,删除线性表的第i个元素
void PrintList(); //遍历操作,按序号依次输出各元素
private:
DateType data[MaxSize]; //存放数据元素的数组
int length; //线性表的长度
};
template<class DateType> //顺序表有参构造函数SeqList
SeqList<DataType>::SeqList(DataType a[],int n)
{
if(n>MaxSize)
throw"参数非法";
for(i=0;i<n;i++)
data[i]=a[i];
length=n;
}
template<class DataType> //顺序表按位查找算法Get
DataType SeqList<DataType>::Get(int i)
{
if(i<1&&i>length)
throw"查找位置非法";
else
return data[i-1];
}
template<class DataType> //顺序表插入算法
void SeqList<DataType>::Insert(int i,DataType x)
{
if(length>=MaxSize)
throw"上溢";
if(i<1||i>length+1)
throw"位置";
for(j=length;j>=i;j--)
data[j]=data[j-1]; //注意第j个元素存在于数组下标为j-1处
data[i-1]=x;
length++;
}
template<class DataType> //顺序表删除算法Delete
void SeqList<DataType>::Delete(int i)
{
if(length==0)
throw"下溢";
if(i<1||i>length)
throw"位置";
x=data[i-1]; //取出位置i的元素
for(j=i;j<length;j++)
data[j-1]=data[j]; //注意此处j已经是元素所在的数组下标
length--;
return x;
}