基础数据结构——不定长顺序表

b.不定长顺序表的实现

同样,先给出结构体的定义部分:

typedef int ELEMTYPE;
#define INIT_SIZE 10	//默认初始长度

typedef struct DSqlist
{
	ELEMTYPE*data;
	int length;		//有效空间长度
	int listsize;	//当前最大长度
}DSqlist, * PDSqlist;

简单函数的定义:

//初始化
void Init_sqlist(PDSqlist plist)
{
	assert(plist != NULL);

	plist->data = (ELEMTYPE*)malloc(sizeof(ELEMTYPE) * INIT_SIZE);
	if (plist->data == NULL)
	{
		exit(1);
	}
	plist->length = 0;
	plist->listsize = INIT_SIZE;
}
//扩容
void Inc(PDSqlist plist)
{
	assert(plist != NULL);
	//1.5倍扩容	
	plist->data = (ELEMTYPE*)realloc(plist->data, sizeof(ELEMTYPE) * plist->listsize * 1.5);
	if (plist->data == NULL)
	{
		return;
	}
	plist->listsize *= 1.5;
}
//打印
void Print_sqlist(PDSqlist plist)
{
	assert(plist != NULL);

	for (int i = 0; i < plist->length; i++)
	{
		printf("%d ", plist->data[i]);
	}
	printf("\n");
}
//按位置插入
bool Insert_pos(PDSqlist plist, int pos, int val)
{
	assert(plist != NULL);
	assert(pos >= 0 && pos <= plist->length);

	if (IsFull(plist))	//判满
	{
		Inc(plist);
	}

	for (int i = plist->length - 1; i >= pos; i--)
	{
		plist->data[i + 1] = plist->data[i];
	}
	plist->data[pos] = val;
	plist->length++;
	return true;
}
//按值删除
bool Del_val(PDSqlist plist, int val)
{
	assert(plist != NULL);
	//是否空
	if (IsEmpty(plist))
	{
		return false;
	}

	int pos = Search_val(plist, val);
	if (pos == -1)	return false;
	else
	{
		Del_pos(plist, pos);
	}
	return true;
}
//按位置删除
bool Del_pos(PDSqlist plist, int pos)
{
	assert(plist != NULL);
	assert(pos > 0 && pos <= plist->length);

	for (int i = pos; i < plist->length - 1; i++)
	{
		plist->data[i] = plist->data[i + 1];
	}
	plist->length--;
	return true;
}
//查找val的结点
int Search_val(PDSqlist plist, int val)
{
	assert(plist != NULL);

	for (int i = 0; i < plist->length; i++)
	{
		if (plist->data[i] == val)
			return i;
	}
	return -1;
}
//判空
bool IsEmpty(PDSqlist plist)
{
	assert(plist != NULL);

	return plist->length == 0;
}
//判满
bool IsFull(PDSqlist plist)
{
	assert(plist != NULL);

	return plist->length == plist->listsize;
}
//清空
bool Clear(PDSqlist plist)
{
	assert(plist != NULL);

	plist->length = 0;
	return true;
}
//销毁
bool Destory(PDSqlist plist)
{
	assert(plist != NULL);

	free(plist->data);
	plist->data = NULL;
	plist->length = plist->listsize = 0;
	return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值