当前位置: 首页 > article >正文

【数据结构】栈的创建

Stack.h

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>

//创建栈的结构体
typedef int STDateType;
typedef struct Stack
{
	STDateType* a;
	int top;
	int capacity;
}ST;

//栈的初始化
void STInit(ST* pst);

//栈的销毁
void STDesTroy(ST* pst);

//栈的添加
void STPush(ST* pst, STDateType x);

//栈的删除
void STPop(ST* pst);

//判断栈是否为空
bool STEmpty(ST* pst);

//获取栈中元素的个数
int STSize(ST* pst);

//获取栈顶元素
STDateType STTop(ST* pst);

Stack.c

#include"Stack.h"

//栈的初始化
void STInit(ST* pst)
{
	assert(pst);
	pst->a = NULL;
	pst->top = 0;
	pst->capacity = 0;
}

//栈的销毁
void STDesTroy(ST* pst)
{
	assert(pst);
	free(pst->a);
	pst->top = pst->capacity = 0;
	pst = NULL;
}

//栈的添加
void STPush(ST* pst, STDateType x)
{
	assert(pst);
	//判断是否要开辟空间
	if (pst->top == pst->capacity)
	{
		int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
		STDateType* tmp = (STDateType*)realloc(pst->a, sizeof(STDateType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail:");
			exit(1);
		}
		pst->capacity = newcapacity;
		pst->a = tmp;
	}
	pst->a[pst->top] = x;
	pst->top++;
}

//栈的删除
void STPop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);
	pst->top--;
}

//判断栈是否为空
bool STEmpty(ST* pst)
{
	assert(pst);
	if (pst->top != 0)
		return true;
	return false;
}

//获取栈中元素的个数
int STSize(ST* pst)
{
	assert(pst);
	return pst->top;
}

//获取栈顶元素
STDateType STTop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);
	return pst->a[pst->top - 1];
}

test.c

#include"Stack.h"

void STTest()
{
	ST pst;
	//栈的初始化
	STInit(&pst);
	//入栈
	STPush(&pst, 1);
	STPush(&pst, 2);
	STPush(&pst, 3);
	STPush(&pst, 4);
	STPush(&pst, 5);
	printf("%d ", STTop(&pst));
	STPop(&pst);
	printf("%d ", STTop(&pst));
	STPop(&pst); 
	//判断是否为空
	bool d = STEmpty(&pst);
	if (d)
	{
		printf("\n不为空\n");
	}
	else
	{
		printf("\n为空\n");
	}
	//查询栈中还有几个元素
	int x = STSize(&pst);
	printf("有%d个元素", x);

	//栈的销毁
	STDesTroy(&pst);
}

int main()
{
	STTest();
	return 0;
}

http://www.kler.cn/news/356828.html

相关文章:

  • Redis --- 第六讲 --- 关于持久化
  • nodejs使用redis工具类示例
  • YoloV9改进策略:主干网络改进|DeBiFormer,可变形双级路由注意力|全网首发
  • stm32通过串口读取JY61 JY62数据(HAL库)
  • URP学习(一)
  • 机器学习核心功能:分类、回归、聚类与降维
  • AJAX——POST 设置请求体参数
  • IP基本原理
  • 【nlp】知识蒸馏Distilling
  • Postman发送GET、POST请求
  • 【重学 MySQL】七十二、轻松掌握视图的创建与高效查看技巧
  • 网络爬虫自动化Selenium模拟用户操作
  • Python知识点:基于Python工具,如何使用Ethereum Tester进行智能合约测试
  • python中else使用汇总
  • docker启动MySQL容器失败原因排查记录
  • 力扣 142.环形链表Ⅱ【详细解释】
  • C#的自定义对话框和提示窗体 - 开源研究系列文章
  • Shell脚本:用户和用户组管理全面指南
  • 如何用代码将网页打开
  • Hbase安装及使用