数据结构---栈

栈的定义

栈就类似弹夹中的子弹一样先进去,却要后出来,而最后一个进弹夹的子弹却是第一个被射出来的
在这里插入图片描述
栈只允许在一端进行操作 一端称为栈顶 另一端成为栈底
不含任何数据元素的栈称为空栈。栈又称为先进后出的线性表
栈的插入操作叫做进栈/压栈/入栈
栈的删除操作叫做出栈/弹栈 如上图所示
接下来就定义一个栈的结构

typedef int DataType;
typedef struct stack
{
	DataType* a;
	int top;//栈顶
	int capacity;//容量
}stack;

初始化栈

void StackInit(stack* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

入栈

void StackPush(stack* ps, DataType x)
{
	assert(ps);
	//检查容量
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : (ps->capacity) * 2;
		DataType* tmp = (DataType*)realloc(ps->a, sizeof(stack) * newcapacity);//realloc如果是空指针,则该函数的行为类似于malloc
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}

	//入栈
	ps->a[ps->top] = x;
	ps->top++;

}

出栈

void StackPop(stack* ps)
{
	assert(ps);
	assert(ps->top > 0);
	--(ps->top);
}

获取栈顶元素

DataType StackTop(stack* ps)
{
	assert(ps);
	//栈顶元素是top前一个
	return ps->a[ps->top-1];
}

获取有效元素个数

	int StackSize(stack* ps)
{
	assert(ps);
	return ps->top;
}

判断是否为空栈

bool StackEmpty(stack* ps)
{
	assert(ps);
	return ps->top == 0 ? true : false;
}

销毁栈

void StackDestory(stack* ps)
{
	assert(ps);
	free(ps->a);
	ps->a == NULL;
	ps->capacity = ps->top = 0;
}

以上就是关于栈的基本知识了 希望大佬指正

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++下等马

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值