实现栈的各种基本运算的算法(数据结构)

栈的特点是先入后出,后进先出。

(1)静态栈的创建

cpp 复制代码
//静态栈

#define 10 N
#define int STDataType

typedef struct ST{
    STDataType a[N];
    int top;//栈顶元素
}Stack;

(2)动态栈的创建(本文代码基于动态栈)

cpp 复制代码
//动态栈
#define int STDataType

typedef struct ST {
	STDataType* _a;
	int _top;//栈顶元素
	int _capacity;//最大容量
}Stack;

(3)初始化栈

cpp 复制代码
//初始化栈
void StackInit(Stack* pst)
{
	assert(pst);
	pst->_a = NULL;
	pst->_top = 0;
	pst->_capacity = 0;
}

(4)入栈

cpp 复制代码
//入栈
void StackPush(Stack* pst, STDataType x)
{
	assert(pst);
	if (pst->_top == pst->_capacity)
	{
		STDataType newcapacity = pst->_capacity == 0 ? 4 : (pst->_capacity * 2);
		STDataType* temp = (STDataType*)realloc(pst->_a, sizeof(STDataType) * newcapacity);
		if (temp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		pst->_a = temp;
		pst->_capacity = newcapacity;
	}
	pst->_a[pst->_top] = x;
	pst->_top++;
}

(5)出栈

cpp 复制代码
//出栈
void StackPop(Stack* pst)
{
	assert(pst);
	assert(pst->_top > 0);
	pst->_top--;
}

(6)获取栈顶元素

cpp 复制代码
//获取栈顶元素
STDataType StackTop(Stack* pst)
{
	assert(pst);
	assert(pst->_top>0);
	return pst->_a[pst->_top-1];
}

(7)获取栈的有效个数

cpp 复制代码
//出栈
void StackPop(Stack* pst)
{
	assert(pst);
	assert(pst->_top > 0);
	pst->_top--;
}

(8)判断栈是否为空

cpp 复制代码
//判断栈是否为空,是返回1,非空返回0
bool StackEmpty(Stack* pst)
{
	assert(pst);
	if (pst->_top == 0)
		return true;
	else
		return false;
}

(9)打印栈

cpp 复制代码
//打印栈
void StackPrint(Stack* pst)
{
	while (!StackEmpty(pst))
	{
		printf("%d\n", StackTop(pst));
		StackPop(pst);
	}
}

(10)销毁栈

cpp 复制代码
//销毁栈
void StackDestory(Stack* pst)
{
	assert(pst);
	free(pst->_a);
	pst->_a = NULL;
	pst->_top = pst->_capacity = 0;
}
相关推荐
丶Darling.5 分钟前
26考研 | 王道 | 数据结构 | 第八章 排序
数据结构·考研·排序算法
BB_CC_DD13 分钟前
四. 以Annoy算法建树的方式聚类清洗图像数据集,一次建树,无限次聚类搜索,提升聚类搜索效率。(附完整代码)
深度学习·算法·聚类
我的golang之路果然有问题23 分钟前
快速了解redis,个人笔记
数据库·经验分享·redis·笔记·学习·缓存·内存
我也不曾来过11 小时前
list底层原理
数据结构·c++·list
embedded_w1 小时前
U8G2在PC端模拟(C语言版本)
c语言
梁下轻语的秋缘2 小时前
每日c/c++题 备战蓝桥杯 ([洛谷 P1226] 快速幂求模题解)
c++·算法·蓝桥杯
Angindem2 小时前
SpringClound 微服务分布式Nacos学习笔记
分布式·学习·微服务
CODE_RabbitV2 小时前
【深度强化学习 DRL 快速实践】逆向强化学习算法 (IRL)
算法
虾球xz2 小时前
游戏引擎学习第244天: 完成异步纹理下载
c++·学习·游戏引擎
BOB-wangbaohai2 小时前
Flowable7.x学习笔记(十四)查看部署流程Bpmn2.0-xml
xml·笔记·学习