1. 程式人生 > >線性表1-順序表

線性表1-順序表

線性表 線性 sta move amp cto 入參 let i++

順序表屬於線性表的一種存儲表現形式,在計算機內部表示為一段連續的內存空間,數組就是一種順序表。

下面是順序表的主要操作:

  1 //順序表的基本操作
  2 template <typename Type> class Vector {
  3 private:
  4     //size為容量,length為當前元素個數
  5     int size,length;
  6     Type *data;
  7 public:
  8     //構造函數
  9     Vector(int input_size) {
 10         size=input_size;
 11
length=0; 12 data=new Type[size]; 13 } 14 15 //析構函數 16 ~Vector() { 17 delete[] data; 18 } 19 20 //插入函數 21 bool insert(int loc, Type value) { 22 if (loc < 0 || loc > length) { 23 return false; 24 } 25 if
(length >= size) { 26 expand(); 27 } 28 for (int i = length; i > loc; --i) { 29 data[i] = data[i - 1]; 30 } 31 data[loc] = value; 32 length++; 33 return true; 34 } 35 36 // 擴容函數 37 void expand(){ 38
Type *old_data=data; 39 //這裏將容量擴為原來的2倍 40 size=size*2; 41 data=new Type[size]; 42 for(int i=0;i<length;i++){ 43 data[i]=old_data[i]; 44 } 45 delete[] old_data; 46 } 47 48 //查找函數,找到則返回下標,否則返回-1 49 //傳入參數:const防止其被修改,&避免傳入後重新創建參數浪費空間 50 int search(const Type &value) { 51 for(int i=0;i<length;i++){ 52 if(data[i]==value){ 53 return i; 54 } 55 } 56 return -1; 57 } 58 59 //刪除指定位置的元素 60 bool remove(int index) { 61 if(index<0||index>=length){ 62 return false; 63 } 64 for(int i=index+1;i<length;i++){ 65 data[i-1]=data[i]; 66 } 67 length--; 68 return true; 69 } 70 71 //遍歷函數 72 void print() { 73 for(int i=0;i<length;i++){ 74 if(i>0){ 75 cout<<" "; 76 } 77 cout<<data[i]; 78 } 79 cout<<endl; 80 } 81 82 //獲取指定位置的元素 83 Type get_data(int loc){ 84 if(loc<0||loc>=length){ 85 cout<<"failed"<<endl; 86 return 0; 87 } 88 return data[loc]; 89 } 90 91 //修改指定位置的元素 92 bool change_data(int loc,Type new_data){ 93 if(loc<0||loc>=length){ 94 return false; 95 } 96 data[loc]=new_data; 97 return true; 98 } 99 100 int get_length(){ 101 return length; 102 } 103 104 //將順序表左移k位 105 void left_shift(int k){ 106 if(k<=0||k>=length){ 107 return; 108 } 109 Type *temp=new Type[k]; 110 for(int i=0;i<k;i++){ 111 temp[i]=data[i]; 112 } 113 for(int i=k;i<length;i++){ 114 data[i-k]=data[i]; 115 } 116 for(int i=0;i<k;i++){ 117 data[i+length-k]=temp[i]; 118 } 119 delete[] temp; 120 } 121 122 }; 123 124 125 //求兩個遞增集合的交集:從第一個元素開始往後比較,小的往後繼續走,相等的就加入記錄結果的Vector中 126 void intersect(Vector<int> &listA, Vector<int> &listB, Vector<int> &intersection){ 127 int length_A=listA.get_length(),length_B=listB.get_length(); 128 int i_a=0,i_b=0,i_c=0; 129 while(i_a<length_A&&i_b<length_B){ 130 if(listA.get_data(i_a)<listB.get_data(i_b)){ 131 i_a++; 132 } 133 else if(listA.get_data(i_a)>listB.get_data(i_b)){ 134 i_b++; 135 } 136 else{ 137 intersection.insert(i_c, listA.get_data(i_a)); 138 i_a++; 139 i_b++; 140 i_c++; 141 } 142 } 143 }

線性表1-順序表