顺序表的增删改查等基本操作的实现

typedef int SLDateType;
typedef struct SeqList
{
	SLDateType* a;
	size_t size;
	size_t capacity; // unsigned int
}SeqList;
// 对数据的管理:增删查改 
void SeqListInit1(SeqList* ps)
{
	if (ps == NULL)
		return;
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}
//销毁
void SeqListDestory1(SeqList* ps)
{
	free(ps->a);
	ps->a = NULL;
}
//打印
void SeqListPrint1(SeqList* ps)
{
	if (ps == NULL)
		return;
	int size = ps->size;
	for (int i = 0; i < size; i++)
	{
		printf("%d ", ps->a[i]);
	}
}
//检查容量
void Checkcapacity1(SeqList* ps)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 1 : 2 * ps->capacity;
			int* newa = (int*)realloc(ps->a, sizeof(int)*newcapacity);//realloc会自动释放原来的空间
			ps->a = newa;
			ps->capacity = newcapacity;
	}
}
//尾插
void SeqListPushBack1(SeqList* ps, SLDateType x)
{
	if (ps == NULL)
		return;
	//检查容量
	Checkcapacity1(ps);
	ps->a[ps->size] = x;
	ps->size++;
}
//头插
void SeqListPushFront1(SeqList* ps, SLDateType x)
{
	if (ps == NULL)
		return;
	Checkcapacity1(ps);
	int end = ps->size;
	while (end)
	{
		ps->a[end] = ps->a[end - 1];
	}
	ps->a[0] = x;
}
//头删
void SeqListPopFront1(SeqList* ps)
{
	if (ps == NULL || ps->size == 0)
		return;
	int start = 1;
	while (start < ps->size)
	{
		ps->a[start - 1] = ps->a[start];
		++start;
	}
	--ps->size;
}
//尾删
void SeqListPopBack1(SeqList* ps)
{
	if (ps == NULL)
		return;
	ps->size--;
}
// 顺序表查找
int SeqListFind1(SeqList* ps, SLDateType x)
{
	Checkcapacity1(ps);
	size_t i = 0;
	for(i;i<ps->size;++i)
	{
		if (ps->a[i] == x)
			return i;
    }
	return 0;
}
// 顺序表在pos位置插入x
void SeqListInsert1(SeqList* ps, int pos, SLDateType x)
{
	if (ps == NULL)
		return;
	Checkcapacity1(ps);
	int end = ps->size;
	while (end > pos)
	{
		ps->a[end] = ps->a[end - 1];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}
// 顺序表删除pos位置的值
void SeqListErase1(SeqList* ps, size_t pos)
{
	if (ps == NULL)
		return;
	Checkcapacity1(ps);
	while (pos < ps->size -1)
	{
		ps->a[pos] = ps->a[pos + 1];
		pos++;
	}
	ps->size--;
}
void main()
{
	SeqList ps;
	SeqListInit1(&ps);
	SeqListPushBack1(&ps, 1);
	SeqListPushBack1(&ps, 2);
	SeqListPushBack1(&ps, 3);
	SeqListPushBack1(&ps, 4);
	SeqListPushBack1(&ps, 5);
	SeqListPrint1(&ps);
	printf("\n");
	SeqListPopBack1(&ps);
	SeqListPrint1(&ps);
	printf("\n");
	SeqListPopFront1(&ps);
	SeqListPrint1(&ps);
	printf("\n");
	SeqListInsert1(&ps, 2, 6);
	SeqListPrint1(&ps);
	printf("\n");
	SeqListErase1(&ps, 2);
	SeqListPrint1(&ps);
	printf("\n");
	int i = SeqListFind1(&ps, 1);
	printf("%d ", i);
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值