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

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

(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;
}
相关推荐
于小汐在咯42 分钟前
词根学习笔记 | Agri系列
笔记·学习
Swift社区1 小时前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
霜绛1 小时前
Unity:Json笔记——Json文件格式、JsonUtlity序列化和反序列化
学习·unity·json·游戏引擎
tt5555555555552 小时前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展
让我们一起加油好吗2 小时前
【基础算法】DFS中的剪枝与优化
算法·深度优先·剪枝
Q741_1472 小时前
C++ 模拟题 力扣495. 提莫攻击 题解 每日一题
c++·算法·leetcode·模拟
我命由我123453 小时前
Excel - Excel 列出一列中所有不重复数据
经验分享·学习·职场和发展·word·powerpoint·excel·职场发展
璞致电子3 小时前
fpga开发板ZYNQ 璞致 PZ7010/7020 邮票孔核心板简介-ZYNQ7000系列小系统学习板
linux·嵌入式硬件·学习·fpga开发·fpga·fpga开发板·xilinx开发板
Felven3 小时前
A. Be Positive
算法
小O的算法实验室3 小时前
2026年COR SCI2区,自适应K-means和强化学习RL算法+有效疫苗分配问题,深度解析+性能实测,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进