程序 = 算法 + 数据结构
程序设计 = 算法 + 数据结构 + 编程范式
数据结构 = 结构定义 + 结构操作
malloc(); // 动态申请空间
calloc(); // 动态申请空间&清空
realloc(); // 重新申请空间
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define COLOR(b, a) "\033[" #b "m" a "\033[0m" // 字符串的拼接:#b 表示将 b 字符串化
#define RED(a) COLOR(31, a)
#define GREEN(a) COLOR(32, a)
//结构定义:顺序表
typedef struct Vector {
int *data;
int size, length;
} Vec;
//结构操作
Vec *init(int size);
int clear(Vec *vec);
int expand(Vec *vec);
int insert(Vec *vec, int index, int val);
int erase(Vec *vec, int index);
int output(Vec *vec);
int main() {
srand(time(0));
#define MAX_N 20
Vec *vec = init(1);
for (int i = 0; i < MAX_N; i++) {
int op = rand() % 4; // 75% 的概率插入元素
int index = rand() % (vec->length + 1);
int val = rand() % 100;
switch (op) {
case 0:
case 1:
case 2: {
printf("insert %d at %d to the Vector = %d\n", val, index, insert(vec, index, val));
} break;
case 3: {
printf("erase a item at %d = %d\n", index, erase(vec, index));
} break;
}
output(vec), printf("\n");
}
#undef MAX_N
clear(vec);
return 0;
}
//结构操作:初始化顺序表
Vec *init(int size) {
Vec *vec = (Vec *)malloc(sizeof(Vec));
vec->data = (int *)malloc(sizeof(int) * size);
vec->size = size;
vec->length = 0;
return vec;
}
//结构操作:销毁顺序表
int clear(Vec *vec) {
if (vec == NULL) return 0;
free(vec->data);
free(vec);
return 1;
}
//结构操作:动态扩容
int expand(Vec *vec) {
int extra_size = vec->size;
int *temp;
while (extra_size) {
temp = (int *)realloc(vec->data, sizeof(int) * (vec->size + extra_size));
if (temp != NULL) break;
extra_size >>= 1;
}
if (temp == NULL) return 0;
vec->data = temp;
vec->size += extra_size;
return 1;
}
//结构操作:插入元素
int insert(Vec *vec, int index, int val) {
if (vec == NULL) return 0;
if (vec->length == vec->size) {
if (expand(vec)) {
printf(GREEN("success to expand! the size = %d\n"), vec->size);
} else {
printf(RED("fail to expand!\n"));
return 0;
}
}
if (index < 0 || index > vec->length) return 0;
for (int i = vec->length - 1; i >= index; i--) {
vec->data[i + 1] = vec->data[i];
}
vec->data[index] = val;
vec->length += 1;
return 1;
}
//结构操作:删除元素
int erase(Vec *vec, int index) {
if (vec == NULL) return 0;
if (index < 0 || index >= vec->length) return 0;
for (int i = index + 1; i < vec->length; i++) {
vec->data[i - 1] = vec->data[i];
}
vec->length -= 1;
return 1;
}
//结构操作:输出所有元素
int output(Vec *vec) {
if (vec == NULL) return 0;
printf("[");
for (int i = 0; i < vec->length; i++) {
i && printf(", "); // 末尾无空格操作
printf("%d", vec->data[i]);
}
printf("]\n");
return 1;
}
标签:index,顺序,Vec,int,vec,return,向量,size
From: https://www.cnblogs.com/Kelvin-Wu/p/16795292.html