#include<iostream> #include<assert.h> using namespace std;
template<class T> class LinearList { public: LinearList(); ~LinearList(); //创建一个空线性表 void Create(); //空表检查 bool IsEmpty() const; //返回表的长度(元素个数) int Length(); //寻找表中第k个元素,并把它保存到x中,如果不存在,则返回false bool Find(int, T&); //返回元素x在表中的位置,如果不在表中,则返回0 int Search(T&) const; //删除表中第k个元素,并把它保存到x中 void Delete(int,T&); //在第k个元素之后插入x,返回修改后的线性表 LinearList<T>&Insert(int, const T&); //把线性表放入输出流out中 //ostream& operator<<(ostream& out,const LinearList<T> & x){} private: int length; int MaxSize; T* Link; }; //构造函数 template<class T> LinearList<T>::LinearList() { //cout<<"请输入你的数据有多少:"<<endl; //cin>>MaxSize; this->MaxSize = MaxSize; Link = new T[MaxSize]; Length = 0; } //析构函数 template<class T> LinearList<T>::~LinearList() { delete [] Link; } //创建一个空线性表 template<class T> void LinearList<T>::Create() { Link = new T[MaxSize]; length = 0; } //空表检查 template<class T> bool LinearList<T>::IsEmpty() const { assert(Length < 0); return (0 != Length); } //抽数 template<class T> bool LinearList<T>::Find(int k,T& x) { // have no the findElement if(k<1 || k > Length) return false;
x = Link[k-1]; return true; } //查询 template<class T> int LinearList<T>::Search(T& x) const { for(int i = 0;i < length;i++) if(Link[i] == x) return ++i;
return -1; }
//删除 template<class T> void LinearList<T>::Delete(int k,T& x) { if(Find(k,x)) { for(int i = k;i<length;i++) Link[i-1] = Link[i];
length--; } }
//插入 template<class T> LinearList<T>& LinearList<T>::Insert(int k,const T& x ) { if(k<0||k>length) { cout<<"位置错误."<<endl; //return; 引发异常 }
if(length == MaxSize) { cout<<"数据已满,无法再接纳数据"<<endl; //return ; 引发异常 }
length++;
for(int i = length-1;i > k; i--) Link[i+1] = Link[i];
Link[k] = x; return *this; } template<class T> int LinearList<T>::Length() { return length; } int main() { LinearList<int> L(5); L.Create(); cout<<"长度:"<<L.Length()<<endl; cout<<"插入表:"<<endl; L.Insert(1,2); cout<<"插入后元素后的长度:"<<L.Length()<<endl; L.Search(2); return 0; }