It relates to the sequence table + deletions expansion (which say nothing directly look at the code)
/*************************************************************************
> File Name: 1.cpp
> Author:
> Mail:
> Created Time: 2020年02月12日 星期三 10时35分04秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct vector{
int *data;
int size, length;
}Vector;
Vector *init(int n){
Vector *vec = (Vector *)malloc(sizeof(Vector));
vec->data = (int *)malloc(sizeof(int) * n);
vec->size = n;
vec->length = 0;
return vec;
}
void clear(Vector *vec){
if(vec == NULL) return ;
free(vec->data);
free(vec);
return ;
}
int expand(Vector *vec){
int extra_size = vec->size;
int *p;
while(extra_size){
p = (int *)realloc(vec->data, sizeof(int) * (extra_size + vec->size));
if(p) break;
extra_size /= 2;
}
if(p == NULL) return 0;
vec->data = p;
vec->size += extra_size;
return 1;
}
int insert(Vector *vec, int loc, int val){
if(vec == NULL) return 0;
if(loc < 0 || loc > vec->length) return 0;
if(vec->length == vec->size){
if(!expand(vec)) return 0;
printf("expand successfully ! size = %d\n", vec->size);
}
for(int i = vec->length; i > loc; i--){
vec->data[i] = vec->data[i - 1];
}
vec->data[loc] = val;
vec->length++;
return 1;
}
int erase(Vector *vec, int loc){
if(vec == NULL) return 0;
if(loc < 0 || loc >= vec->length) return 0;
for(int i = loc + 1; i < vec->length; i++){
vec->data[i - 1] = vec->data[i];
}
vec->length--;
return 1;
}
void output(Vector *vec){
printf("Vector(%d) = [", vec->length);
for(int i = 0; i < vec->length; i++){
i && printf(", ");
printf("%d", vec->data[i]);
}
printf("]\n");
return ;
}
int main(){
srand(time(0));
#define max_op 20
Vector *vec = init(1);
int op, loc, val;
for(int i = 0; i < max_op; i++){
op = rand() % 4;
loc = rand() % (vec->length + 3) - 1;
val = rand() % 100;
switch(op) {
case 0:
case 1:
case 2: {
printf("insert %d at %d to Vector = %d\n", val, loc, insert(vec, loc, val));
}break;
case 3: {
printf("erase item at %d from Vector = %d\n", loc, erase(vec, loc));
}break;
}
output(vec);
printf("\n");
}
clear(vec);
return 0;
}