顺序表(一)

 顺序表本质:数组

 顺序表的定义

typedef int SLDatatype;
typedef struct Seqlist
{
	SLDatatype* a;
	int size;//存储的有效数据的个数
	int capacity;//容量
}SL;

 顺序表的增删改查

 顺序表的初始化

void SLInit(SL* psl)//初始化
{
	/*psl->a = NULL;
	psl->size = 0;
	psl->capacity = 0;*/

	psl->a = (SLDatatype*)malloc(sizeof(SLDatatype) * 4);
	if (psl->a == NULL)
	{
		perror("malloc fail");
		return;
	}
	psl->capacity = 4;
	psl->size = 0;
}

 顺序表的销毁

void SLDestory(SL* psl)//销毁
{
	free(psl->a);
	psl->a = NULL;
	psl->capacity = 0;
	psl->size = 0;
}

 顺序表的插入 

void SLCheckcapacity(SL* psl)//检查容量大小
{
	if (psl->capacity == psl->size)
	{
		SLDatatype* tmp = (SLDatatype*)realloc(psl->a, sizeof(SLDatatype) * psl->capacity * 2);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		psl->a = tmp;
		psl->capacity *= 2;
	}
}
void SLPushBack(SL* psl, SLDatatype x)//尾插
{
	//判断容量
	SLCheckcapacity(psl);
	psl->a[psl->size] = x;
	psl->size++;
}

void SLPushFront(SL* psl, SLDatatype x)//头插
{
	SLCheckcapacity(psl);
	int end = psl->size - 1;
	while (end >= 0)
	{
		psl->a[end + 1] = psl->a[end];
		--end;
	}
	psl->a[0] = x;
	psl->size++;
}

void SLInsert(SL* psl, int pos, SLDatatype x)//任意位置插入
{
	assert(pos >= 0 && pos <= psl->size);
	//判容量
	SLCheckcapacity(psl);

	//先挪数据(从后往前挪)
	int end = psl->size - 1;
	while (end >= pos)
	{
		psl->a[end + 1] = psl->a[end];
		--end;
	}
	//后插入
	psl->a[pos] = x;
	psl->size++;
}

 顺序表的删除

void SLPopFront(SL* psl)//头删
{
	assert(psl->size > 0);
	int start = 0;
	while (start < psl->size)
	{
		psl->a[start] = psl->a[start + 1];
		++start;
	}
	psl->size--;
}

void SLPopBack(SL* psl) //尾删
{
	//判断是否为空
	assert(psl->size>0);
	psl->size--;
}

void SLErase(SL* psl, int pos)//任意位置删除
{
	assert(pos >= 0 && pos <= psl->size);
	int end = pos+1;
	while (end < psl->size)
	{
		psl->a[end-1] = psl->a[end];
		end++;
	}
	psl->size--;
}

 顺序表的查找,修改和打印


void SLPrint(SL* psl)//打印
{
	for (int i = 0;i < psl->size;i++)
	{
		printf("%d  ", psl->a[i]);
	}
}

int SLFind(SL* psl, SLDatatype x)//查找
{
	for (int i = 0;i < psl->size;i++)
	{

		if (psl->a[i] == x)
		{
			return i;
		}
	}
	return -1;

}

void SLModify(SL* psl, int pos, SLDatatype x)//修改
{
	assert(pos >= 0 && pos <= psl->size);

	psl->a[pos] = x;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值