/* * Copyright (c) 2010,hnu-software * All rights reserved. * * 文件名称:AListe.h * 文件标识:.h * 摘 要:顺序表 * * 当前版本:1.1 * 作 者:www * 完成日期: */ #ifndef AList_h__ #define AList_h__ const int DefaultSize = 100; template <class Elem> class AList { public: AList(int sz = DefaultSize):MaxSize(sz),CurrentSize(-1) { if (sz > 0) { m_elements = new Elem[MaxSize]; } } ~AList() { delete []m_elements; } int Length() { return CurrentSize + 1; } void clear()//Reset the AList { delete []m_elements; m_elements = new Elem[MaxSize]; CurrentSize = -1; } bool Find(Elem target, int &pos); //Find position of target bool IsExist(Elem target);//Whether target is in the AList bool append(Elem target);//Add element at the end of AList bool Insert(Elem target, int pos);//Insert target in the pos-th position bool Remove(Elem target);//Remove target form AList bool IsEmpty();//Whether the AList is empty bool IsFull();//Whether the AList is full Elem GetValue(int pos);//Get the pos-th data void print(); private: Elem *m_elements; const int MaxSize; int CurrentSize; }; template<class Elem> bool AList<Elem>::Find(Elem target, int &pos) { for (int i = 0; i < CurrentSize; i++) { if (m_elements[i] != target) continue; else { pos = i; return true; } } return false; } template<class Elem> bool AList<Elem>::IsExist(Elem target) { int temp; return Find(target, temp); } template<class Elem> bool AList<Elem>::Insert(Elem target, int pos) { if (pos < 0 || pos > MaxSize-1 || pos > CurrentSize + 1) { return false; } else for (int i = CurrentSize; i > pos; i--) { m_elements[i] = m_elements[i - 1]; } m_elements[pos] = target; CurrentSize ++; return true; } template<class Elem> bool AList<Elem>::append(Elem target) { if (IsFull()) return false; else m_elements[CurrentSize + 1] = target; CurrentSize ++; return true; } template<class Elem> bool AList<Elem>::IsEmpty() { return CurrentSize == -1; } template<class Elem> bool AList<Elem>::IsFull() { return CurrentSize == MaxSize -1; } template<class Elem> bool AList<Elem>::Remove(Elem target) { int pos; if (!Find(target,pos)) return false; for (int i = pos; i < CurrentSize; i++) { m_elements[i] = m_elements[i + 1]; } CurrentSize --; return true; } template<class Elem> void AList<Elem>::print() { cout<<endl<<endl; cout<<endl<<"<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl; for(int i = 0; i < CurrentSize + 1; i++) { if(i % 3 == 0) cout<<endl; cout<<m_elements[i]<<"/t"; } cout<<endl<<"<<<<<<<<<<<<<<<<<<<<<<<<<<<<"<<endl; cout<<endl<<endl; } #endif // AList_h__