线性表存储在计算机中可以采用多种方式,以下是按照顺序存储方式实现:
优点:查找很方便
缺点:插入元素、删除元素比较麻烦,时间复杂度 O(n)
1 #ifndef SeqList_h 2 #define SeqList_h 3 #include4 using namespace std; 5 const int MAXSIZE = 1000; 6 template 7 class SeqList{ 8 public: 9 SeqList(){length = 0;} //初始化10 SeqList(const T a[], int n); //初始化11 int GetLength(){ return length;} //获取长度12 void PrintList(); //打印13 void Insert(int i, T x); //插入14 T Delete(int i); //删除15 T Get(int i); //获取16 int Locate(T x); //按值查找17 private:18 int length;19 T data [MAXSIZE];20 21 };22 template 23 SeqList ::SeqList(const T a[], int n){24 if(n>MAXSIZE){25 throw "数组长度超过顺序表的最大长度";26 }27 for(int i = 0;i 33 void SeqList ::PrintList(){34 cout<<"按序号依次遍历线性表中的各个数据元素:"< 41 void SeqList ::Insert(int i, T x){42 if(length>MAXSIZE) throw "上溢异常";43 if(i<0 || i>length-1) throw "位置异常";44 for(int j = length; j>=i; j--){45 data[j] = data[j-1];46 }47 data[i-1] = x;48 length ++;49 }50 template 51 T SeqList ::Delete(int i){52 if(length == 0) throw "下溢异常";53 if(i<1 || i>length){54 throw "位置异常";55 }56 T x = data[i-1];57 for(int j = i-1;j 64 T SeqList ::Get(int i){65 if(0 == length) throw"上溢异常";66 if(i<1 || i>length){67 throw "查找位置非法";68 }69 return data[i-1];70 }71 template 72 int SeqList ::Locate(const T x){73 for(int i = 0;i