间接寻找表就是建立一个指针数组,所以,既柔和了链表插入,删除的优先,又有随机访问的特性 #include<iostream> #include<string> using namespace std; class Exception { private: string mid; public: Exception( string a ):mid(a){}; string& GetString(){ return mid;} }; template< typename T > class IndirectList { private: T **Table; int Size , MaxSize; public: IndirectList( int MaxSize = 10 ); ~IndirectList(); bool IsEmpty()const{return Size == 0 ;} int Length()const{return Size;} void Clear(); bool Find( int k , T&x )const; int Search( const T & x )const; IndirectList<T>& Delete( int k , T & x ); IndirectList<T>& Insert(int k , const T&x ); template< typename T> friend ostream& operator<<( ostream & , const IndirectList<T> & a ); }; template<typename T> IndirectList<T>::IndirectList( int MaxSize = 10 ) { Table = new T*[MaxSize*10]; for( int i = 0 ; i <= MaxSize ; ++i ) Table[i] = new T; Size = 0 ; this->MaxSize = MaxSize; } template<typename T> IndirectList<T>::~IndirectList() { for( int i = 0 ; i <= MaxSize ; ++i ) delete Table[i]; delete [] Table; } template<typename T> void IndirectList<T>::Clear() { Size = 0 ; } template<typename T> bool IndirectList<T>::Find( int k , T&x )const { if( k < 1 || k > Size ) return false; x = *Table[k-1]; return true; } template<typename T> int IndirectList<T>::Search( const T & x )const { int i; *Table[Size] = x; for( i = 0 ; *Table[i] != x ; ++i ); if( i == Size ) return 0; else return i+1; } template<typename T> IndirectList<T>& IndirectList<T>::Delete( int k , T & x ) { int i; if( k < 1 || k > Size ) throw Exception("OutOfBound"); T* mid = Table[k-1]; x = *Table[k-1]; for( i = k ; i < Size ; ++i ) { //cout<< i <<" "<<i -1 <<endl; Table[i-1] = Table[i]; } Table[ Size - 1 ] = mid; --Size; return *this; } template<typename T> IndirectList<T>& IndirectList<T>::Insert(int k , const T&x ) { int i; if( k < 0 || k > Size ) throw Exception("OutOfBound"); T* mid = Table[Size]; for( i = Size - 1; i >= k ; --i ) Table[i+1] = Table[i]; Table[k] = mid; *Table[k] = x; ++Size; return *this; } template<typename T> ostream& operator<<( ostream & os , const IndirectList<T> & a ) { for( int i = 0 ; i != a.Size ; ++i ) os<< *a.Table[i]<<" "; return os; }