線性表存儲在計算機中可以采用多種方式,以下是按照順序存儲方式實現:
優點:查找很方便
缺點:插入元素、刪除元素比較麻煩,時間復雜度 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 */