0
点赞
收藏
分享

微信扫一扫

顺序表的相关函数试做(含注释)

yundejia 2022-02-05 阅读 55

 含注释,有不足的地方,感谢指正!

#include<stdio.h>
#include<stdlib.h>
typedef struct vector
{
	int* data;
	int size, length;
}vector;//创建并重定义vector节点


vector* init(int n)//创建大小为n的顺序表
{
	vector* vec = (vector*)malloc(sizeof(vector));
	vec->data = (int*)malloc(sizeof(int) * n);
	vec->size = n;
	vec->length = 0;
	return vec;
}


void insert(vector* vec, int ind, int val)//在index位置插入元素value
{
	if (vec == NULL) 
	{
		printf("错误!vec是空指针\n"); return;
	}
	if (vec->data == NULL) 
	{
		printf("错误!vec->data是空指针\n"); return;
	}
	if (vec->length >= vec->size)
	{
		printf("错误!顺序表已满\n\a");
		return;
	}
	if (ind<0 || ind>vec->length)
	{
		printf("错误!输入点正常数字啊!\n\a"); return;
	}//预测可能出现的问题,防止出错或内存泄漏
		for (int i = vec->length; i > ind; i--)
			vec->data[i] = vec->data[i - 1];//把要插入位置后面的每一个元素向后移一位
		vec->data[ind] = val;
		vec->length++;//长度加一
		if (vec->data[ind] == val)printf("插入成功!\n");
}


void erase(vector* vec, int ind)//擦除index位置
{
	if (vec == NULL)
	{
		printf("错误!vec是空指针"); return;
	}
	if (vec->data == NULL)
	{
		printf("错误!vec->data是空指针"); return;
	}
	if (vec->length == 0)printf("没元素可删,length为0!");


	if (ind < 0 || ind >= vec->length)	
	{
		printf("错误!输入点正常数字啊\n"); return;
	}
	//预测可能出现的问题,防止出错或内存泄漏

	
	for (int i = ind + 1; i < vec->length; i++)
		vec->data[i] = vec->data[i - 1];
	vec->length--;
}

vector* expand(vector* vec,int n)//顺序表的扩容
{
	int* p = NULL;
	p = (int*)realloc(vec->data, sizeof(int) * n);
	if (p == NULL)
	{
		printf("错误,申请失败");
		return 0;
	}
	vec->data = p;
	vec->size = n;
	printf("扩容完毕,扩容后的大小size=%d\n", vec->size);
	return vec;
}

void clear(vector* vec)//顺序表的清除操作
{
	if (vec == NULL)
		printf("是个空指针");
	free(vec->data);
	free(vec);
	vec->data = NULL;
	vec = NULL;
}

void output(vector* vec)//顺序表的输出
{
	printf("length=%d\n", vec->length);
	printf("size=%d\n", vec->size);
	printf("arry=[%d,", vec->data[0]);
	for (int i = 1; i < vec->length - 1; i++)
		printf("%d,", vec->data[i]);
	printf("%d]", vec->data[vec->length - 1]);
}
举报

相关推荐

0 条评论