线性表存储在计算机中可以采用多种方式,以下是按照顺序存储方式实现:
优点:查找很方便
缺点:插入元素、删除元素比较麻烦,时间复杂度 O(n)
1 #ifndef SeqList_h 2 #define SeqList_h 3 #include <iostream> 4 using namespace std; 5 const int MAXSIZE = 1000; 6 template <class T> 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 <class T> 23 SeqList<T>::SeqList(const T a[], int n){ 24 if(n>MAXSIZE){ 25 throw "数组长度超过顺序表的最大长度"; 26 } 27 for(int i = 0;i<n;i++){ 28 data[i] = a[i]; 29 } 30 length = n; 31 } 32 template <class T> 33 void SeqList<T>::PrintList(){ 34 cout<<"按序号依次遍历线性表中的各个数据元素:"<<endl; 35 for(int i = 0;i<length;i++){ 36 cout << data[i] <<" "; 37 } 38 cout << endl; 39 } 40 template <class T> 41 void SeqList<T>::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 <class T> 51 T SeqList<T>::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<length-1;j++){ 58 data[j]= data[j+1]; 59 } 60 length --; 61 return x; 62 } 63 template <class T> 64 T SeqList<T>::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 <class T> 72 int SeqList<T>::Locate(const T x){ 73 for(int i = 0;i<length;i++){ 74 if(x == data[i]) 75 return i+1; 76 } 77 return 0; 78 } 79 #endif /* SeqList_h */