首页 > 技术文章 > 顺序表

yaoxc 2013-09-04 14:18 原文

  1 #include <iostream>
  2 using namespace std;
  3 #define MAXLENGTH 20
  4 
  5 typedef struct LineList
  6 {
  7     int Array[MAXLENGTH];
  8     int curLength;
  9 }LineList;
 10 
 11 bool initial(LineList* elem)
 12 {
 13     elem->Array[0] = 0;
 14     elem->curLength = 0;
 15     return true;
 16 }
 17 
 18 //--------------------------
 19 //elem:要插入的元素
 20 //n:要插入的位置
 21 //---------------------------
 22 bool insert(LineList* array,int n,int elem)
 23 {
 24     if (n > array->curLength)
 25     {
 26         cout<<"error!"<<endl;
 27         return false;
 28     }
 29     if (array->curLength+1 == MAXLENGTH)
 30     {
 31         cout<<"overflow!"<<endl;
 32         return false;
 33     }
 34 
 35     //第一个元素不要了,从下标1开始计算
 36     //第一个元素用于保存元素个数(int类型时)
 37     for (int i= array->curLength ; i != n ;i-- )
 38     {
 39         array->Array[i+1] =  array->Array[i];
 40     }
 41     array->Array[i+1] = elem;
 42 
 43     array->curLength++;
 44     return true;
 45 }
 46 
 47 //删除位置n处的值
 48 bool deleteex(LineList* array,int* elem,int n )
 49 {
 50     if (n > array->curLength || n <= 0 )
 51     {
 52         cout<<"error!"<<endl;
 53         return false;
 54     }
 55     
 56     *elem= array->Array[n];
 57 
 58     for (int i = n ; i< array->curLength;i++)
 59     {
 60          array->Array[i] = array->Array[i+1];
 61     }
 62     array->curLength--;
 63     return true;
 64 }
 65 
 66 bool search(LineList *array ,int *elem,int n)
 67 {
 68     if (n<= 0 || n > array->curLength)
 69     {
 70         cout<<"error!"<<endl;
 71         return false;
 72     }
 73     *elem = array->Array[n];
 74     return true;
 75 }
 76 
 77 bool modify(LineList *array,int elem, int n)
 78 {
 79     if (n<= 0 || n>array->curLength)
 80     {
 81         cout<<"error!"<<endl;
 82         return false;
 83     }
 84     array->Array[n] = elem;
 85     return true;
 86 
 87 }
 88 void print(LineList array)
 89 {
 90     for (int i = 1 ; i <= array.curLength;i++)
 91     {
 92         cout<<array.Array[i]<<endl;;
 93     }
 94 }
 95 
 96 int main()
 97 {
 98     LineList array;
 99     initial(&array);
100     if(!insert(&array,0,2))
101     {
102         return -1;
103     }
104     insert(&array,0,1);
105     print(array);
106     cout<<"-------------------------"<<endl;
107     int ele;
108     deleteex(&array,&ele,1);
109     print(array);
110     cout<<"-------------------------"<<endl;
111     if(search(&array,&ele,1))
112     {
113         cout<<ele<<endl;
114     }
115 
116     cout<<"---------------------"<<endl;
117     if (modify(&array,5,1))
118     {
119         print(array);
120     }
121     
122     return 0 ;
123 }

 

 

 

推荐阅读