栈的简单实现

 完整代码:
        

#define _CRT_SECURE_NO_WARINGS 1
//栈的实现
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>

typedef struct Stack
{
	int* a;
	int top;
	int capacity;
}ST;

//初始化
void StackInit(ST* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->top = ps->capacity = 0;
}

//插入数据
void StackPush(ST* ps,int x)
{
	assert(ps);
	//先判断是否满了
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		//创建一个临时数组
		ST* tmp = (int*)relloc(ps->a, sizeof(int) * newcapacity);
		if (tmp == NULL)
		{
			printd("realloc fail");
			exit(-1);
		}
		else
		{
			ps->a = tmp;//将tmp给给ps->a
			ps->capacity = newcapacity;
		}
	}
	ps->a[ps->top] = x;
	ps->top++;
}

//删除数据
void StackPop(ST* ps)
{
	assert(ps);
	//先判断是否为空才能删除
	ps->top--;
}

//判断栈
bool StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == 0;
}

//返回栈顶的元素
int StackTop(ST* ps)
{
	assert(ps);
	assert(!Empty(ps));
	return ps->a[ps->top - 1];
}

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

//元素个数
int StackSize(ST* ps)
{
	assert(ps);
	return ps->top;
}
void testST()
{
	ST ps;
	StackInit(&ps);//初始化
	StackPush(&ps,1);//插入数据
	StackPop(&ps);//删除数据
	bool ret = StackEmpty(&ps);//判断是否为空
	int ans = StackTop(&ps);//返回栈顶的元素
	StackDestory(&ps);
	int size = StackSize(&ps);
}
int main()
{
	testST();
	return 0;
}

如有错误,多多指教!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值