线性表的建立
#include <iostream>
using namespace std;
const int MaxSize=100;
template<class DateType>
class SepList
{
public:
SepList(){length=0;};
SepList(DateType a[],int n);
~SepList(){};
int Length(){return length;}
DateType Get(int i);
int Locate(DateType x);
void Insert(int i,DateType x);
DateType Delete(int i);
int Empty();
void PrintList();
private:
int length;
DateType date[MaxSize];
};
template<class DateType>
SepList<DateType>::SepList(DateType a[],int n)
{
if(n>MaxSize) throw "参数非法";
for(int i=0;i<n;i++){
date[i]=a[i];
}
length=n;
}
template<class DateType>
DateType SepList<DateType>::Get(int i)
{
if(i<1||i>length) throw "查找位置非法";
else return date[i-1];
}
template<class DateType>
int SepList<DateType>::Locate(DateType x)
{
int i=0;
while(i<length)
{
if(date[i]==x)
return(i+1);
i++;
}
return 0;
}
template<class DateType>
void SepList<DateType>::Insert(int i,DateType x)
{
if(length>=MaxSize) throw"上溢";
if(i<1||i>length+1) throw"位置";
for(int j=length;j>=i;j--){
date[j]=date[j-1];
}
date[i-1]=x;
length++;
}
template<class DateType>
DateType SepList<DateType>::Delete(int i)
{
if(length==0) throw"下溢";
if(i<1||i>length) throw"位置";
DateType x=date[i-1];
for(int j=i;j<length;j++)
date[j-1]=date[j];
length--;
return x;
}
template<class DateType>
void SepList<DateType>::PrintList()
{
for(int i=0;i<length;i++)
cout<<date[i]<<" ";
cout<<endl;
}
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,0};
SepList<int>temp(a,10);
cout<<"顺序表长度:"<<temp.Length()<<endl;
cout<<"第i个元素:"<<temp.Get(5)<<endl;
cout<<"值为x的元素的位置:"<<temp.Locate(2)<<endl;
temp.Insert(5,4);
cout<<"顺序表长度:"<<temp.Length()<<endl;
cout<<"第i个元素:"<<temp.Get(5)<<endl;
cout<<"值为x的元素的位置:"<<temp.Locate(2)<<endl;
cout<<"被删除的元素是:"<<temp.Delete(2)<<endl;
cout<<"顺序表长度:"<<temp.Length()<<endl;
cout<<"第i个元素:"<<temp.Get(5)<<endl;
cout<<"值为x的元素的位置:"<<temp.Locate(2)<<endl;
temp.PrintList();
cout<<"顺序表长度:"<<temp.Length()<<endl;
return 0;
}