标签:
C++Primer后面的高级特性看不下去,重新找了一本数据结构的书来看,加油!!书名叫《数据结构算法与C++语言描述》!
基本完成插入,查找,删除,打印,哦,对了,那个operator<<的重载感觉似懂非懂!!!
参考代码如下:
#include<iostream> //using namespace std; template<class T> class LinearList{ public: LinearList(int maxListSize = 0); ~LinearList(){ } bool IsEmpty(){return bool(length); }; int Length(){return length; }; bool Find(int k,T& x); int Search(const T& a) const; LinearList<T>& Delete(int k,T &x); LinearList<T>& Insert(int k,T& x); void OutPut(std::ostream &out)const; private: int length; int MaxSize; T *element; }; template<class T> LinearList<T>::LinearList(int MaxLS){ MaxSize = MaxLS; length = 0; element = new T[MaxLS]; } template<class T> bool LinearList<T>::Find(int k, T &x){ if(k>MaxSize||k<0)return false; x = element[k-1]; return true; } template<class T> int LinearList<T>::Search(const T &a)const{ for(int i = 0;i < MaxSize; ++i){ if(element[i] == a)return i++; } return 0; } template<class T> LinearList<T>& LinearList<T>::Delete(int k,T &x){ if(this->Find(k,x)){ for(int i = k-1;i<MaxSize;i++){ element[i-1] = element[i]; } length = length - 1; std::cout<<length<<std::endl; return *this; } } template<class T> LinearList<T>& LinearList<T>::Insert(int k,T &x){ if(length == MaxSize){ std::cout<<"FULL!"<<std::endl;} for(int i = MaxSize;i > k-1;i--){ element[i] = element[i-1]; } element[k] = x; length++; return *this; } template<class T> void LinearList<T>::OutPut(std::ostream &out)const{ for(int i = 0;i < length;i++) out<<element[i]<<" "; } template<class T> std::ostream& operator<<(std::ostream& out,const LinearList<T>& a) { a.OutPut(out); return out; } int main() { int ftest = 0; LinearList<int> ll(5); for(int i = 0; i< 5; ++i){ int temp = i * i; ll.Insert(i,temp); } std::cout<<ll.Length()<<std::endl; std::cout<<ll<<std::endl; ll.Find(2,ftest); std::cout<<ftest<<std::endl; ll.Delete(2,ftest); std::cout<<ll.Length()<<std::endl; std::cout<<ll<<std::endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/ashen/p/4419015.html