1 #include <stdio.h>
2 #include <malloc.h>
3 #include <stdlib.h>
4
5 typedef struct Arr
6 {
7 int * pBase = NULL; //数组首地址
8 int cnt; //当前元素个数
9 int len; //数组大小
10 } Array, *pArray;
11
12
13 bool init_array(pArray arr, int len);
14 bool append(pArray arr, int val);
15 bool is_empty(pArray arr);
16 bool is_full(pArray arr);
17 void sort(pArray arr);
18 void reversal(pArray arr);
19 void show_array(pArray arr);
20 bool insert(pArray arr, int pos, int val); //pos 表示第一个元素。例如 pos=2,表示第二个元素。但是下标是1
21 bool del(pArray arr, int pos, int * val); // int * val保存删除的元素
22
23
24 int main(){
25
26 getchar();
27 return 0;
28
29 }
30
31 bool is_full(pArray arr){
32 return arr->cnt == arr->len;
33 }
34
35 bool is_empty(pArray arr){
36 return arr->cnt == 0;
37 }
38
39
40
41 bool init_array(pArray arr, int len){
42 if (len <= 0) {
43 printf("len is too small");
44 return false;
45 }
46
47 arr->pBase = (int*)malloc(sizeof(int)*len);
48 if (NULL == arr->pBase){
49 printf("init array is fail");
50 return false;
51 }
52 else{
53 arr->cnt = 0;
54 arr->len = len;
55 return true;
56 }
57
58
59 }
60
61 bool append(pArray arr, int val){
62 if (is_full(arr)){
63 return false;
64 }
65 arr->pBase[arr->cnt] = val;
66 arr->cnt++;
67 return true;
68 }
69
70
71 void sort(pArray arr){
72 for (int i = 0; i < arr->cnt; i++) {
73 for (int j = 0; j < arr->cnt - 1 - i; j++) {
74 if (arr->pBase[j] > arr->pBase[j + 1]) {
75 int temp = arr->pBase[j];
76 arr->pBase[j] = arr->pBase[j + 1];
77 arr->pBase[j + 1] = temp;
78 }
79 }
80 }
81 }
82
83
84 void show_array(pArray arr){
85
86 if (is_empty(arr)){
87 printf("array is empty");
88 }
89 else{
90 for (int i = 0; i < arr->cnt; i++) {
91 printf("%d ", arr->pBase[i]);
92 }
93 }
94
95 }
96
97 void reversal(pArray arr){
98 int i = 0;
99 int j = arr->cnt - 1;
100 while (i < j){
101 int temp = arr->pBase[i];
102 arr->pBase[i] = arr->pBase[j];
103 arr->pBase[j] = temp;
104 i++;
105 j--;
106 }
107 }
108
109
110 bool insert(pArray arr, int pos, int val){
111 if (is_full(arr)){
112 printf("array is full");
113 return false;
114 }
115
116 if (pos<0 || pos>arr->cnt + 1){
117 return false;
118 }
119
120 for (int i = arr->cnt - 1; i >= pos - 1; i--) {
121 arr->pBase[i + 1] = arr->pBase[i];
122 }
123 arr->pBase[pos - 1] = val;
124 arr->cnt++;
125 return true;
126 }
127
128
129 bool del(pArray arr, int pos, int * val){
130 if (is_empty(arr)){
131 printf("array is empty");
132 return false;
133 }
134
135 if (pos<0 || pos>arr->cnt){
136 return false;
137 }
138
139 *val = arr->pBase[pos - 1];
140
141 for (int i = pos; i < arr->cnt; i++){
142 arr->pBase[i - 1] = arr->pBase[i];
143 }
144 arr->cnt--;
145 return true;
146
147 }