顺序表
结构定义:
类似数组,多出两种属性
1.size = 9
2.count = 5
创建数据类型
typedef struct vector { // size 记录动态顺序表申请空间的大小
int size, count; // count 记录顺序表当前有效的数据个数
int *data;
} vector;
创建一个顺序表
vector *getNewVector(int n) {
vector *p = (vector *)malloc(sizeof(vector));
p->size = n;
p->count = 0;
p->data = (int *)malloc(sizeof(int) * n);
return p;
}
在顺序表中插入数据
int insert (vector *v, int pos, int val) { //在pos位置插入val
if (pos < 0 || pos > v->count) return 0;
if (v->size == v->count && !expand(v)) {
return 0;
}
for (int i = v->count - 1; i >= pos; i--) { //一定要逆序遍历
v->data[i + 1] = v->data[i];
}
v->data[pos] = val;
v->count += 1;
return 1;
}
为数据表添加自动扩容功能
int expand(vector *v) {
if (v == NULL) return 0;
int *p = (int *)realloc(v->data, sizeof(int) * 2 * v->size);
if (p == NULL) return 0;
v->data = p;
v->size *= 2;
return 1;
}
添加删除功能
int earse(vector *v, int pos) {
if (pos < 0 || pos >= v->count) return 0;
for (int i = pos + 1; i < v->count; i++) {
v->data[i - 1] = v->data[i];
}
v->count -= 1;
return 1;
}
删除数据表
void clear(vector *v) {
if (v == NULL) return ;
free(v->data);
free(v);
return ;
}