顺序表的初始化、长度、插入、删除、取出等

  1 #include <stdio.h>
  2 #define MaxSzie 100
  3 
  4 typedef int DataType;
  5 typedef struct
  6 {
  7     DataType list[MaxSzie];
  8     int size;
  9 }SeqList;
 10 
 11 void ListInit(SeqList *L)
 12 {
 13     L->size = 0;
 14 }
 15 
 16 int ListLength(SeqList L)
 17 {
 18     return L.size;
 19 }
 20 
 21 int ListInsert(SeqList *L, int i, DataType x)
 22 {
 23     int j=0;
 24 
 25     if (i>=MaxSzie)
 26     {
 27         printf("error!");
 28         return 0;
 29     }
 30     else if (i<0||i>L->size)
 31     {
 32         printf("error!");
 33         return 0;
 34     }
 35     else
 36     {
 37         while (j<i)
 38         {
 39             j++;
 40         }
 41         if (j!=i)
 42         {
 43             printf("error!");
 44             return 0;
 45         }
 46         else
 47         {
 48             for ( j; j < L->size; j++)
 49             {
 50                 L->list[j + 1] = L->list[j];
 51             }
 52             L->list[j] = x;
 53             L->size++;
 54             return 1;
 55         }
 56     }
 57 }
 58 
 59 int ListDelete(SeqList *L, int i, DataType *x)
 60 {
 61     int j = 0;
 62 
 63     if (i>=MaxSzie)
 64     {
 65         printf("error!");
 66         return 0;
 67     }
 68     else if (i<0 || i>L->size)
 69     {
 70         printf("error!");
 71         return 0;
 72     }
 73     else
 74     {
 75         while (j < i)
 76         {
 77             j++;
 78         }
 79         if (j != i)
 80         {
 81             printf("error!");
 82             return 0;
 83         }
 84         else
 85         {
 86             *x = L->list[j];
 87             for (j; j < L->size; j++)
 88             {
 89                 L->list[j] = L->list[j + 1];
 90             }
 91             L->size--;
 92             return 1;
 93         }
 94     }
 95 }
 96 
 97 int ListGet(SeqList *L, int i, DataType *x)
 98 {
 99     if (i<0||i>L->size-1)
100     {
101         printf("error!");
102         return 0;
103     }
104     else
105     {
106         *x = L->list[i];
107         return 1;
108     }
109 }
110 //主函数
111 int main()
112 {
113     SeqList mylist;
114     int i, j,x;
115 
116     ListInit(&mylist);
117     for ( i = 0; i < 10; i++)
118     {
119         if (ListInsert(&mylist, i, i + 1)==0)
120         {
121             printf("error!");
122         }
123     }
124     if (ListDelete(&mylist,4,&x)==0)
125     {
126         printf("error!");
127 
128     }
129     else
130     {
131         printf("Delete Number>>>%d\n", x);
132     }
133     for ( j = 0; j <ListLength(mylist); j++)
134     {
135         if (ListGet(&mylist,j,&x)==0)
136         {
137             printf("error!");
138         }
139         else
140         {
141             printf("%d    ",x);
142         }
143     }
144     getchar();
145     return 0;
146 }

猜你喜欢

转载自www.cnblogs.com/leime/p/9477810.html
今日推荐