数据结构之栈的实现

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前期准备

1.头文件

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

typedef int STDataType;

typedef struct Stack
{
	STDataType* a;
	int top;//栈顶
	int capacity;//容量
}ST;
//初始化
void StackInit(ST* ps);
//销毁
void StackDestory(ST* ps);
//入栈
void StackPush(ST* ps, STDataType x);
//出栈
void StackPop(ST* ps);
//栈顶元素
STDataType StackTop(ST* ps);
//元素个数
int StackSize(ST* ps);
//判空
bool StackEmpty(ST* ps);

1.初始化

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

2.销毁

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

一、入栈和出栈

1.入栈

//入栈
void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	if (ps->capacity == ps->top)//判断容量是否为满
	{
		int newnode = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType)*newnode);
		if (tmp == NULL)
		{
			printf("realloc fail");
			exit(-1);
		}
		ps->capacity = newnode;
		ps->a = tmp;
	}
	ps->a[ps->top] = x;
	ps->top++;
}

2.出栈

//出栈
void StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));//断言看是否为空
	ps->top--;
}
在这里插入代码片

二、栈顶元素、元素个数和判空

1.栈顶元素

//栈顶元素
STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));//断言看是否为空
	return ps->a[ps->top-1];
}

2.元素个数

//元素个数
int StackSize(ST* ps)
{
	assert(ps);
	return ps->top;
}

3.判空

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

三、实现

void test()
{
	ST s;
	StackInit(&s);
	StackPush(&s, 1);
	StackPush(&s, 2);
	StackPush(&s, 3);
	printf("%d ", StackTop(&s));
	StackPop(&s);
	StackPush(&s, 4);
	StackPush(&s, 5);
	while (!StackEmpty(&s))
	{
		printf("%d ", StackTop(&s));
		StackPop(&s);
	}
	StackDestory(&s);
}
int main()
{
	test();
	return 0;
}

在这里插入图片描述

总结

以上为栈的实现的全部内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值