快速掌握栈基本操作

栈学习目标

  • 快速掌握栈基本操作

学习内容:

  1. 栈操作相关代码
  2. 结果
  3. 备注

学习产出:

1.栈相关代码

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>

/*
栈遵循后进先出规则
*/

//动态定义
typedef int STDataType;
typedef struct Stack{
	STDataType* array;//数据用数组存放
	int top;//栈顶
	int capacity;//容量
}ST;

//初始化
void StackInit(ST* ps)
{
	//一定不能为空的可用断言处理
	assert(ps);
	//为数组动态分配一定空间,如果分配后的array为空,表示分配失败,退出
	ps->array = (STDataType*)malloc(sizeof(STDataType)*4);
	if (ps->array == NULL)
	{
		printf("malloc fail!\n");
		exit(-1);
	}
	//初始top为0,表示指针指向栈顶元素的下一个,初始top为-1,表示指针指向栈顶元素
	ps->capacity = 4;
	ps->top = 0;
}

//入栈,栈顶插入数据
void StackPush(ST* ps,STDataType x)
{
	assert(ps);

	//对栈中元素进行判断,满了就要增容用realloc函数实现重新分配
	if (ps->top == ps->capacity)
	{
		STDataType* tmp = (STDataType*)realloc(ps->array, ps->capacity * 2 * sizeof(STDataType));
		if (tmp == NULL)
		{
			printf("realloc fail!\n");
			exit(-1);
		}
		else
		{
			//将旧数组与容量与重分配后的替换
			ps->array = tmp;
			ps->capacity *= 2;
		}
	}
		//top=0时,先插后加,top=-1时,先加再插(数组下标第一为0)
		ps->array[ps->top] = x;
		ps->top++;	
}

//出栈,栈顶删除数据
void StackPop(ST* ps)
{
	assert(ps);

	//栈空了,调用pop,直接终止程序进行报错
	assert(ps->top > 0);

	//删除栈中数据
	ps->top--;
}

//获取栈顶元素
STDataType StackTop(ST* ps)
{
	assert(ps);
	//栈空了,调用top,直接终止程序报错
	assert(ps->top > 0);

	//top指向栈顶元素下一个,减一后则指向栈顶
	return ps->array[ps->top - 1];
}

//获取栈中有效元素个数
int StackSize(ST* ps)
{
	assert(ps);

	//top指向栈顶元素下一个,根据数组下标可知数组元素个数等于数组下标加一,此处正好为栈顶
	return ps->top;
}

//检测栈中元素是否为空,为空返回非零结果,不为空返回0

bool StackEmpty(ST* ps)
{
	assert(ps);

	//top=0则为真,为空,不等于0,则为假,非空
	return ps->top == 0;
}

//销毁栈
void StackDestroy(ST* ps)
{
	assert(ps);
	free(ps->array);
	ps->array = NULL;
	ps->top = ps->capacity = 0;
}


//测试
int main()
{
	ST st;
	StackInit(&st);
	StackPush(&st, 1);
	StackPush(&st, 2);
	StackPush(&st, 3);
	StackPush(&st, 4);
	StackPush(&st, 5);
	while (!StackEmpty(&st))
	{
		//输出栈顶元素,并将输出后的元素删除,使得前一个入栈的元素成为新的栈顶
		printf("%d ", StackTop(&st));
		StackPop(&st);
	}
	printf("\n");
	StackDestroy(&st);

	return 0;
}在这里插入代码片

2.运行结果
在这里插入图片描述

3.备注
(1)有关栈的基本操作解释部分均为自己在学习过程中的理解进行补充,水平有限,有理解错误的地方还请各位不吝赐教~
(2)这是小白发表的第一篇CSDN文章,后续会多加学习,进一步完善丰富文章内容,尽量做到更详细的解释与说明~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值