顺序表及扩容

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <time.h>

typedef struct Vector {
	int *data;
	int size;
	int length;
} Vec;

Vec *init(int n) {
	Vec *v = (Vec *)malloc(sizeof(Vec));
	v->data = (int *)malloc(sizeof(int) * n);
	v->size = n;
	v->length = 0;
	return v;
}

int expand(Vec *v) {
	if (!v) return 0;
	int extr_size = v->size;
	int *p = NULL;
	while (extr_size) {
		p = (int *)realloc(v->data, sizeof(int) * (v->size + extr_size));
		if (p) break;
		extr_size /= 2;
	} 
	if (!extr_size) return 0;
	v->data = p;
	v->size += extr_size;
	return 1;
}

#if 0
int expand(Vec *v) {
	int *tmp = v->data;
	v->data = (int *)malloc(sizeof(int) * v->size * 2);
	v->size *= 2;
	memcpy(v->data, tmp, v->length * sizeof(int));
	free(tmp);
	return 1;
}
#endif
int insert(Vec *v, int val, int ind) {
	if (!v) return 0;
	if (ind < 0 || ind > v->length) return 0;
	if (v->length >= v->size) {
		if (!expand(v)) return 0;
		printf("success to expand! Vector size is %d\n", v->size);
	}
	for (int i = v->length; i > ind; i--) {
		v->data[i] = v->data[i - 1];
	}
	v->data[ind] = val;
	v->length++;
	return 1;
}

int erase(Vec *v, int ind) {
	if (!v) return 0;
	if (ind < 0 || ind >= v->length) return 0;
	for (int i = ind + 1; i < v->length; i++) {
		v->data[i - 1] = v->data[i];
	}
	v->length--;
	return 1;
}

void clear(Vec *v) {
	if (!v) return ;
	free(v->data);
	free(v);
	return ;
}

void output(Vec *v) {
	if (!v) return;
	printf("Vector : [");
	for (int i = 0; i < v->length; i++) {
		i && printf(" ");
		printf("%d", v->data[i]);
	}
	printf("]\n");
}

int main() {
	srand(time(0));
#define max_op 30
	Vec *vec = init(max_op / 3);
	for (int i = 0; i < max_op; i++) {
		int val = rand() % 100;
		int ind = rand() % (vec->length + 3) - 1;
		int op = rand() % 10;
		switch (op) {
			case 0 ... 8: {
				printf("insert %d at %d to Vector = %d\n", val, ind, insert(vec, val, ind));
			} break;
			case 9: {
				printf("erase a iterm at %d from Vector = %d\n", ind, erase(vec, ind));
			} break;
		}
		output(vec);
		printf("\n");
	}
	clear(vec);
#undef max_op

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值