#include<iostream>
#include<cstdio>
using namespace std;
const int MaxSize=100;//顺序表的最大长度
template<class DataType>//将其设成模板,class替换成TypeName也是一样的
class SeqList
{
public:
SeqList(){length=0;};//建立空的顺序表
SeqList(DataType a[],int n);//建立长度为n的顺序表
~SeqList(){};//构析函数
int Length(){return length;};//求线性表的长度
DataType Get(int i);//按位查找,查找第i个元素的值
int Locate(DataType x);//按值查找,查找值为x的元素序号
void Insert(int i,DataType x);//插入操作,在第i个位置插入值为x的元素
DataType Delete(int i);//删除操作,删除第i个元素
int Empty(){
if(length==0)
cout<<"空";
else cout<<"非空";
};//判断线性表是否为空
void PrintList();//遍历操作,按序号依次输出各元素
private:
DataType data[MaxSize];//存放数据元素的数组
int length;//线性表的长度
} ;
template<class DataType>
SeqList<DataType>::SeqList(DataType a[],int n)
{
if(n>MaxSize) throw "wrong parameter";
for(int i=0;i<n;i++)
data[i]=a[i];
length=n;
}
template<class DataType>
DataType SeqList<DataType>::Get(int i)
{
if(i<1&&i>length) throw "wrong location";
else return data[i-1];
}
template<class DataType>
int SeqList<DataType>::Locate(DataType x)
{
for(int i=0;i<length;i++)
if(data[i]==x) return i+1;
return 0;
}
template<class DataType>
void SeqList<DataType>::Insert(int i,DataType x)
{
if(length>=MaxSize) throw "overflow";
if(i<1||i>length+1) throw "wrong location";
for(int j=length;j>=i;j--)
data[j]=data[j-1];
data[i-1]=x;
length++;
}
template <class DataType>
DataType SeqList<DataType>::Delete(int i)
{
int x;
if(length==0) throw "Underflow";
if(i<1 || i>length) throw "wrong Location";
x = data[i-1];
for(int j=i;j<length;j++)
data[j-1] = data[j];
length--;
return x;
}
template <class DataType>
void SeqList<DataType>::PrintList()
{
for(int i=0;i<length;i++)
cout<<data[i]<<" ";
printf("\n");
}
int main()
{
int r[5]={2,6,8,1,11},i,x;
SeqList<int>L(r,5);
cout<<"当前线性表的数据为:";
L.PrintList();
cout<<"下面进行操作:查找第i个元素的值,请输入i:";
cin>>i;
cout<<L.Get(i)<<endl;
cout<<"下面进行操作:查找值为x的元素序号,请输入x:";
cin>>x;
cout<<L.Locate(x)<<endl;
cout<<"下面进行操作:在第i个位置插入值为x的元素,请输入i和x(以空格分开):";
cin>>i>>x;
L.Insert(i,x);
cout<<"当前线性表的数据为:";
L.PrintList();
cout<<"下面进行操作:删除第i个元素,请输入i:";
cin>>i;
L.Delete(i);
cout<<"当前线性表的数据为:";
L.PrintList();
cout<<"线性表空or非空?";
L.Empty();
return 0;
}
运行结果: