【数据结构】顺序栈

一 什么是栈

栈就是一种专有名词,没什么高大上的。栈也是线性表的一种,就同顺序表,链表都是线性表一样。但既然都是顺序表,为啥,分那么多名称呢?我就打个比喻,一个公司,是不是又经理,员工等分工呀?那他们分工为了什么,不就是为了提高效率工作嘛,栈的出现也是这样,为了满足一些特殊场景而设计出来的东西,这个场景就是后进先出的场景,也就是只能在表的一端上的一个元素进行插入和删除操作,我们把仅仅限于在一端插入和删除操作的表叫做栈。顺序栈也就是顺序表的特殊操作,也就是栈,都没啥区别哈。


二 栈的存储结构

typedef int STDataType;

typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}ST;

三 栈的头文件

#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int STDataType;
//栈初始化top = 0;入栈元素后,top指向元素的下一个位置

typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}ST;
//初始化栈
void StackInit(ST* ps);
//入栈
void StackPush(ST* ps,STDataType x);
//出栈
void StackPop(ST* ps);
//获取栈顶元素
STDataType StackTop(ST* ps);
//判断栈是否为空
bool StackIsEmpty(ST* ps);
//销毁栈
void StackDestroy(ST* ps);


栈常用的接口


#include"Stack.h"

void StackInit(ST* ps)
{
	assert(ps);

	ps->a = NULL;
	ps->top = 0;
	ps->capacity = 0;
}
void StackPush(ST* ps, STDataType x)
{
	assert(ps);

	if (ps->capacity == ps->top)
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* temp = (STDataType*)realloc(ps->a, sizeof(STDataType)*newCapacity);
		if (temp == NULL)
		{
			printf("增容失败!程序退出");
			exit(-1);
		}
		//增容成功!
		ps->capacity = newCapacity;
		ps->a = temp;
	}


	ps->a[ps->top++] = x;

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

	ps->top--;;
}

STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	return ps->a[ps->top - 1];
}

bool StackIsEmpty(ST* ps)
{
	assert(ps);
	//if (ps->top == 0)
	//	return true;
	//else
	//	return false;
	//下面这种方式比if判断代码更少
	return ps->top == 0;
}

//遍历取出栈的数据方式
void StackPrint(ST* ps)
{
	assert(ps);

	while (!StackIsEmpty(&ps))
	{
		printf("%d ", ps->a[ps->top - 1]);
		StackPop(&ps); //取完栈顶元素记得弹栈
	}
}

void StackDestroy(ST* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;

}

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

呋喃吖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值