本程序是双倍扩容
顺序表类定义:
1 template<class T> 2 class SeqList :public Linearlist<T> 3 { 4 public: 5 SeqList(int mSize); 6 ~SeqList() 7 { 8 delete[] elements; 9 } 10 bool Insert(int i, T x); 11 private: 12 int maxLength; 13 T *elements; 14 }; 15 16 template <class T> 17 SeqList<T>::SeqList(int mSize) 18 { 19 maxLength = mSize; 20 elements = new T[maxLength]; 21 n = 0; 22 }
插入时若空间不足自动扩容成员函数:
1 template <class T> 2 bool SeqList<T>::Insert(int i, T x) 3 { 4 if (i<-1 || i>n - 1) 5 { 6 cout << "out of bound" << endl; 7 return false; 8 } 9 if (n == maxLength) 10 { 11 T *elements_temp; 12 elements_temp = new T[2 * maxLength]; 13 for (int k = 0; k<n; k++) 14 { 15 elements_temp[k] = elements[k]; 16 } 17 delete[]elements; 18 elements = elements_temp; 19 } 20 for (int j = n - 1; j > i; j--) 21 { 22 elements[j+1 ] = elements[j]; 23 } 24 elements[i+1] = x; 25 n++; 26 return true; 27 }
时间: 2024-11-07 05:16:39