# 003、动态顺序表的插入与删除

  1 #include "stdio.h"
2 #include "stdlib.h"
3
4 #define MAXSIZE 100
5 typedef struct
6 {
7     int* sqelem;
8     int length;
9     int listsize;
10 }sqlist;
11
12 /* 初始化 */
13 int sqListInit(sqlist* L)
14 {
15     int i;
16     L->sqelem = (int*)malloc(MAXSIZE*sizeof(int));
17     if(!L->sqelem)
18     {
19         printf("malloc err!\n");
20         return 0;
21     }
22     L->length = 0;
23     L->listsize = MAXSIZE;
24
25     for(i = 0;i < 10;i++)
26     {
27         *(L->sqelem+i) = i;
28     }
29     L->length = 10;
30     return 1;
31 }
32
33 /* 循环打印 */
34 int printSqList(sqlist* L)
35 {
36     int i;
37     if(!L->sqelem)
38     {
39         printf("L->sqelem is null!\n");
40         return 0;
41     }
42     for(i = 0;i < L->length;i++)
43     {
44         printf("L->sqelem+%d = %d\n",i,*(L->sqelem+i));
45     }
46     printf("L->length = %d\n",L->length);
47     printf("L->listsize = %d\n",L->listsize);
48     return 1;
49 }
50
51 /* 插入数据 */
52 int insertSqList(sqlist* L,int n,int data)
53 {
54     int i;
55     if(n < 0|| n > L->length)
56     {
57         printf("sqlist insertion error!\n");
58         return 0;
59     }
60     /* 超出最大空间 */
61     if(L->length >= L->listsize)
62     {
63         /* 重新调整 L->sqelem 的大小*/
64         L->sqelem = (int*)realloc(L->sqelem,L->listsize+10);
65         if(!L->sqelem)
66         {
67             printf("realloc L->sqelem is null!\n");
68             return 0;
69         }
70         L->listsize += 10;
71     }
72     /* 插入数据 */
73     for(i = L->length -1;i >= n;i--)
74     {
75         *(L->sqelem+i+1) = *(L->sqelem+i);
76     }
77     *(L->sqelem+n) = data;
78     L->length += 1;
79     return 1;
80 }
81
82 /* 删除数据 */
83 int deleteSqList(sqlist* L,int n)
84 {
85     int i;
86     if(n < 0|| n > L->length)
87     {
88         printf("sqlist delete error!\n");
89         return 0;
90     }
91     for(i = n;i < L->length;i++)
92     {
93         *(L->sqelem+i) = *(L->sqelem+i+1);
94     }
95     L->length -= 1;
96     return 1;
97 }
98
99 int main()
100 {
101     sqlist sqLsit1;
102     int err;
103     err = sqListInit(&sqLsit1);
104     if(err)
105         printSqList(&sqLsit1);
106     printf("\n");
107     /* 插入数据 */
108     err = insertSqList(&sqLsit1,5,20);
109     if(err)
110         printSqList(&sqLsit1);
111     printf("\n");
112     /* 删除 */
113     err = deleteSqList(&sqLsit1,5);
114     if(err)
115         printSqList(&sqLsit1);
116     return 0;
117 }

posted @ 2020-05-17 22:34  季风的杜萨  阅读(255)  评论(0编辑  收藏  举报