順序表實現
阿新 • • 發佈:2019-02-19
tle stl bool ble str item ++ 內容 按順序
#include<iostream> using namespace std; template <class T> class LinearList { private: T* element;//存儲順序表的數組 int MaxSize;//順序表的最大長度 int length;//順序表的實際長度 public: //構造函數,若申明順序表實例時未給出表的最大長度,則最大長度為10 LinearList(int); //析構函數 ~LinearList(void) { delete[] element; } //判空 bool ListEmpty(void) const { return length==0; } //判滿 bool ListFull(void) const { return length==MaxSize; } //返回表的長度 int ListLength(void) const { return length; } //存取,將下標為k的節點字段賦值給item bool Find(int,T&) const; //查找,在表中查找字段值為item的結點並返回下標 int Search(const T&) const; //刪除,刪除小標為k的節點後並將其字段值賦值給item bool Delete(int,T&); //插入,在下標為k的節點後插入字段為item的結點 bool Insert(int,const T&); //打印,將順序表內容按順序打印到屏幕 void Print(void); }; //順序表的構造函數 template <class T> LinearList<T>::LinearList(int MaxListSize=10) { MaxSize=MaxListSize; element=new T[MaxSize]; length=0; }; //存取:將下表為k的結點的字段值賦值給item並返回true,若不存在返回false template <class T> bool LinearList<T>::Find(int k,T& item) const { if(k<0||k>length-1||length==0) { cout<<"unreasonable position or empty list!"<<endl; return false; } else { item=element[k]; return true; } } //查找:在表中查找字段為item的結點並返回其下標;若表中沒有item,則返回-1 template <class T> int LinearList<T>::Search(const T& item) const { for(int i=0; i<length; ++i) { if(element[i]==item) return i; } return -1; } //刪除:刪除表中下標為k的結點,並將其值賦給item template <class T> bool LinearList<T>::Delete(int k,T& item) { if(Find(k,item))//若找到下標為k的結點,則將其後面所有結點均向前移動一個位置 { for(int i=k+1; i<length; ++i) element[i-1]=element[i]; length--;//表長度相應減一 return true; } else return false; } //插入,在下標為k的結點後插入item template <class T> bool LinearList<T>::Insert(int k,const T& item) { if(ListFull()) { cout<<"The List is Full!"<<endl; return false; } else if(k<0||k>length) { cout<<"The node does not exist!"<<endl; return false; } else { for(int i=length; i>k; --i) { element[i]=element[i-1]; } element[k]=item; length++; return true; } } //打印 template <class T> void LinearList<T>::Print() { for(int i=0; i<length; ++i) { cout<<element[i]<<"->"; } cout<<endl; } //實例演示 int main() { LinearList<char> list(16); char ch=‘a‘; for(int i=0; i<10; ++i) { list.Insert(i,ch); ch++; } list.Print(); list.Delete(0,ch); list.Print(); list.Insert(list.ListLength(),ch); list.Print(); return 0; }
順序表實現