栈的相关知识

目录

栈的特点:

所需头文件

一.开辟静态栈

 二.开辟动态栈

栈的初始化 

栈的销毁

压栈

出栈

取出栈顶的数据

判空(Empyt)返回值是bool

求元素个数

如果您想打印元素


栈的特点:

先进后出,当然也可以一边进一边出

所需头文件

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>//realloc要用

一.开辟静态栈

typedef int STDataType;
#define N 10
typedef struct stack
{
	STDataType a[N];
	int _top;
}stack

 啊这个不是很好用,所以我们一般不去用它,不过可以给大家了解下哈

 二.开辟动态栈

typedef int STDataType;
typedef struct Stack
{
 STDataType* a;
 int top; // 栈顶
 int capacity; // 容量 
}ST;

栈的初始化 

void STInit(ST* pst)
{
	assert(pst);

	pst->a = NULL;
	// top指向栈顶数据的下一个位置
	pst->top = 0;

	// top指向栈顶数据
	//pst->top = -1;

	pst->capacity = 0;
}

栈的销毁

void STDestroy(ST* pst)
{
	assert(pst);

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

压栈

void STPush(ST* pst, STDataType x)
{
	assert(pst);
	if (pst->capacity == pst->top)
	{
		int newcapacity = pst->capacity == 0 ? 4 : 2 * pst->capacity;
		STDataType* tmp = (STDataType*)realloc(pst, 2 * newcapacity);
		if (tmp == NULL)
		{
			perror("creat fail");
			return;
		}
		pst->a = tmp;
		pst->capacity = newcapacity;
	}
	pst->a[pst->top] = x;
	pst->top++;
}

出栈

void STPop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);

	pst->top--;
}

取出栈顶的数据

STDataType  STTop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);

	return pst->a[pst->top - 1];
}

判空(Empyt)返回值是bool

bool STEmpty(ST* pst)
{
	assert(pst);
	return pst->top == 0;
}

求元素个数

不过我们也知道这里面的top和size是一个含义

int STSize(ST* pst)
{
	assert(pst);
	return pst->top;
}

如果您想打印元素


while (!STEmpty)
{
	printf("%d", STTop(&s));
	STPop(&s);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值