数据结构之栈

一、什么是栈

1.栈的概念

栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFOLast In First Out)的原则。

2.栈的结构

压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据也在栈顶。
在这里插入图片描述

栈的实现

我们今天使用顺序表来实现栈,因为顺序表在尾部插入的时候代价较小。
在这里插入图片描述
在这里插入图片描述

1.结构定义
typedef int STDateType;
typedef struct Stack
{
	STDateType* a;
	int top;
	int capacity;
}ST;
2.栈的初始化
void StackInit(ST* pst);

void StackInit(ST* pst)
{
	assert(pst);
	pst->a = NULL;
	pst->capacity = pst->top = 0;
}
3.压栈

每次在压栈前判断空间是否充足。在第一次给栈4个空间,后续逐步扩大2倍。

void StackPush(ST* pst, STDateType x);

void StackPush(ST* pst, STDateType x)
{
	assert(pst);
	if (pst->capacity == pst->top)
	{
		int NewCapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
		STDateType* tmp = (STDateType*)realloc(pst->a, NewCapacity * sizeof(STDateType));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		pst->a = tmp;
		pst->capacity = NewCapacity;
	}
	pst->a[pst->top] = x;
	pst->top++;
}
4.出栈

注意判断栈是否为空。

void StackPop(ST* pst);

void StackPop(ST* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));//判断
	pst->top--;
}
5.判断栈是否为空

top为0栈即为空。
在这里插入图片描述

bool StackEmpty(ST* pst);

bool StackEmpty(ST* pst)
{
	assert(pst);
	return pst->top == 0;
}
6.访问栈顶数据

top从0开始,注意要减1。
在这里插入图片描述

STDateType StackTop(ST* pst);

STDateType StackTop(ST* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));

	return pst->a[pst->top - 1];
}
7.求栈的大小

在这里插入图片描述
top从0开始,top为多少,栈的大小为多少。

STDateType StackSize(ST* pst);

STDateType StackSize(ST* pst)
{
	assert(pst);
	return pst->top;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值