大概就是用数组模拟动态数组吧,功能包括插入,查询,删除,遍历。可以进行初始化,动态扩容,以及最后释放掉内存
代码如下:
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
typedef struct Vector {
int len, size;
int *q;
} Vector;
void init(Vector *a, int size) {
a -> q = (int *)malloc(sizeof(int) * size);
a -> len = 0;
a -> size = size;
return;
}
void expand(Vector *a) {
a -> size *= 2;
int *old = a -> q;
a -> q = (int *)malloc(sizeof(int) * a -> size);
for (int i = 0; i < a -> len; i++) {
a -> q[i] = old[i];
}
free(old);
return;
}
int insert(Vector *a, int inx, int val) {
if (inx < 0 || inx > a -> len) return ERROR;
if (a -> len >= a -> size) {
expand(a);
}
for (int i = a -> len; i > inx; i--) {
a -> q[i] = a -> q[i - 1];
}
a -> q[inx] = val;
a -> len++;
return OK;
}
int search(Vector *a, int val) {
for (int i = 0; i < a -> len; i++) {
if(a -> q[i] == val) return OK;
}
return ERROR;
}
int delete_node(Vector *a, int inx) {
if (inx < 0 || inx >= a -> len) return ERROR;
for (int i = inx + 1; i < a -> len; i++) {
a -> q[i - 1] = a -> q[i];
}
a -> len--;
return OK;
}
void print(Vector *a) {
for (int i = 0; i < a -> len; i++) {
printf("%d%c", a -> q[i], i == a -> len - 1? '\n': ' ');
}
return;
}
void clear(Vector *a) {
free(a -> q);
free(a);
}
int main() {
Vector *a = (Vector *)malloc(sizeof(Vector));
init(a, 20);
int m, t, p, q;
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &t);
switch (t) {
case 1:
scanf("%d%d", &p, &q);
if (insert(a, p, q)) {
printf("success\n");
} else {
printf("failed\n");
}
break;
case 2:
scanf("%d", &p);
if(delete_node(a, p)) {
printf("success\n");
} else {
printf("failed\n");
}
break;
case 3:
scanf("%d", &p);
if(search(a, p)) {
printf("success\n");
} else {
printf("failed\n");
}
break;
default:
print(a);
}
}
clear(a);
return 0;
}
如果有写的不对或者不全面的地方 可通过主页的联系方式进行指正,谢谢