栈的实现-C语言

栈的实现

栈的实现一般可以用数组或链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入的代价比较小,而链表需要找尾,要遍历链表(单链表)

  1. 定义栈`
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

//静态
#define N 10
typedef int STDataType;
typedef struct Stack
{
	STDataType a[N];
	int top;
}ST;

//动态
typedef int STDataType;
typedef struct Stack
{
	STDataType *a;
	int top;//栈顶
	int capacity;//栈的容量
}ST;
  1. 定义栈所需的功能函数
void StackInit(ST* ps);//栈的初始化
void StackDestory(ST* ps);//销毁栈
void StackPush(ST* ps, STDataType x);//入栈
void StackPop(ST* ps);//出栈
STDataType StackTop(ST* ps);//取栈顶元素
bool StackEmpty(ST* ps);//判断栈是否为空
int StackSize(ST* ps);//计算栈中有多少数据
  1. 实现功能函数
void StackInit(ST* ps)
{
	assert(ps);//判断栈是否为空
	
	//数组为空,栈顶和容量都为0
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;
}

void StackDestory(ST* ps)
{
	assert(ps);

	//释放掉我们开辟的数组的空间,并将地址置为空。
	free(ps->a);
	ps->a = NULL;
	ps->top = ps->capacity = 0;
}

void StackPush(ST* ps, STDataType x)
{
	assert(ps);

	//判断栈满了
	if (ps->top == ps->capacity)
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newCapacity);
		//开辟内存失败直接退出
		if (tmp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newCapacity;
	}
	ps->a[ps->top] = x;
	ps->top++;
}

void StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	ps->top--;
}

STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	//判断栈中有元素,那么栈顶元素的下标为top-1,返回就可以了。
	return ps->a[ps->top - 1];
}

bool StackEmpty(ST* ps)
{
	assert(ps);
	//判断栈是不是空的只需要判断top是不是等于0,是0就是空,就返回真,不是0就返回假
	return ps->top == 0;
}

int StackSize(ST* ps)
{
	assert(ps);
	//top是最后一个数据的下一个位置,因为是数组,下标是从0开始的,所以top就是元素个数。
	return ps->top;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值