#define MaxSize 100
template <class DataType>
class SeqList
{
private:
DataType data[MaxSize];
int length;
public:
SeqList(){length=0;}
SeqList(DataType a[],int n);
~SeqList(){}
int Length(){return length;}
DataType Get(int i);
int Locate(DataType x);
void Insert(DataType x,int i);
DataType Delete(int i);
void PrintList();
};
template <class DataType>
SeqList<DataType>::SeqList(DataType a[],int n)
{
if (n>MaxSize) throw "参数非法";
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 "位置非法";
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>
DataType SeqList<DataType>::Delete(int i)
{
DataType x;
if (length==0) throw "下溢";
if (i<1&&i>length) throw "位置非法";
x=data[i-1];
for (;i<length;i++)
{
data[i-1]=data[i];
}
length--;
return x;
}
template <class DataType>
void SeqList<DataType>::Insert(DataType x,int i)
{
if (i>MaxSize) throw "上溢";
if (i<1&&i>length) throw "位置非法";
for (int j=length;j>=i;j--)
{
data[j]=data[j-1];
data[j-1]=x;
}
length++;
}
template <class DataType>
void SeqList<DataType>::PrintList()
{
cout<<"当前线性表为:"<<endl;
for (int i=0;i<length;i++)
{
cout<<data[i]<<'\t';
}
cout<<endl;
}
#include <iostream>
#include "SeqList.h"
using namespace std;
void main()
{
int a[10]={2,5,4,8,9,1,3,7,6,0};
cout<<"初始化线性表"<<endl;
SeqList<int> sl(a,10);
sl.PrintList();
cout<<sl.Length()<<endl;
cout<<"获取i位元素"<<endl;
cout<<sl.Get(3)<<endl;
cout<<"i位插入元素x"<<endl;
sl.Insert(10,5);
sl.PrintList();
cout<<sl.Length()<<endl;
cout<<"值为x的元素"<<endl;
cout<<sl.Locate(6)<<endl;
cout<<"删除i位元素"<<endl;
cout<<sl.Delete(8)<<endl;
sl.PrintList();
sl.Length();
}