数据结构-线性表的顺序存储

 1 // 线性表的顺序存储
 2 #include <stdio.h>
 3 #define MAXSIZE 101
 4 #define OK 1
 5 #define ERROR 0
 6 #define TRUE 1
 7 #define FALSE 0
 8 typedef int Status;
 9 typedef int ElemType;
10 typedef struct {
11     ElemType data[MAXSIZE];
12     int length; 
13 }SqList;
14 //初始化
15 SqList MakeEmpty(){
16     SqList L;
17     L.length = 0;
18     return L;
19 } 
20 //用e 返回L中的第i个数据元素的值
21 Status GetItem(SqList L,int i,ElemType *e){
22     if(L.length==0 || L.length<i || i<1){
23         return ERROR;
24     }
25     *e = L.data[i-1];
26     return OK;
27 } 
28 // 在L中第i个位置之前插入新的数据元素e,L的长度加1
29 Status InsertItem(SqList *L,int i,ElemType e){
30     int k;
31     if(L->length == MAXSIZE){
32         return ERROR;
33     }
34     if (i<0||i>L->length+1){
35         return ERROR;
36     }
37     if(i<=L->length){
38         for(k=L->length-1;k>=i-1;k--){
39             L->data[k+1]=L->data[k];
40         }
41     }
42     L->data[i-1]=e;
43     L->length++; 
44     return OK;
45 } 
46 //删除操作:删除L中的第i个数据,并用e返回其值
47 Status DeleteItem(SqList *L,int i,ElemType *e){
48     int k ;
49     if(L->length==0){
50         return ERROR;
51     }//线性表为空
52     if(i<1||i>L->length){
53         return ERROR;
54     } //删除位置不正确
55     if(i<L->length){
56         *e=L->data[i-1];
57         for(k=i;k<L->length;k++){
58             L->data[k-1]=L->data[k];
59         }
60     }
61     L->length--;
62     return OK; 
63 } 
64 
65 int main(){
66     SqList L=MakeEmpty();
67     for(int i=0;i<100;i++) 
68     InsertItem(&L,i,i);
69     printf("%d\n",L.length);
70     for(int j=0;j<100;j++){
71         GetItem(L,j,&j);
72         printf("%d\n",j) ; 
73     } 
74     return 0;
75     
76 } 
77 
78 
79  
80  
81  
posted @ 2021-01-14 10:10  wyqgzq  阅读(71)  评论(0)    收藏  举报