[数据结构]——栈的实现(初始化、销毁、入栈、出栈、记录数据总数、判断栈是否为空、获取栈顶数据)

Stack.h

#pragma onece
#include <stdio.h>
#include <assert.h>

typedef int STDataType;

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

void StackInit(Stack *pst); //初始化
void StackDestory(Stack *pst); //销毁
void StackPush(Stack *pst, STDataType x); //插入数据
void StackPop(Stack *pst); //删除数据

int StackSize(Stack *pst); //记录实际数据个数
int StackEmpty(Stack *pst); //判断栈是否为空(是空返回1 非空返回0)
STDataType StackTop(Stack *pst); //获取栈顶数据

Stack.c

#include "Stack.h"

void StackInit(Stack *pst) //初始化
{
	assert(pst);
	pst->a = (STDataType *)malloc(sizeof(STDataType)* 4);
	if (pst->a == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	pst->capacity = 4;
	pst->top = 0;
}

void StackDestory(Stack *pst) //销毁
{
	assert(pst);

	free(pst->a);  //释放 置空 置零
	pst->a = NULL;
	pst->top = pst->capacity = 0;
}


void StackPush(Stack *pst, STDataType x) //插入数据
{
	assert(pst);
	if (pst->top == pst->capacity) //栈满
	{
		STDataType *tmp = realloc(pst->a, pst->capacity * 2 * sizeof(STDataType));
		if (tmp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		pst->a = tmp;
		pst->capacity = pst->capacity * 2; //扩容后记得修改capacity的数值
	}
	pst->a[pst->top] = x;
	pst->top++;
}	

void StackPop(Stack *pst) //删除数据
{
	assert(pst);
	assert(!StackEmpty(pst)); //判断栈是否为空
	--pst->top;
}

int StackSize(Stack *pst) //记录实际数据个数
{
	assert(pst);
	return pst->top;
}

int StackEmpty(Stack *pst) //判断栈是否为空(是空返回1 非空返回0)
{
	assert(pst);
	return pst->top == 0 ? 1 : 0; //注意:判断是否相等为双等号
}

STDataType StackTop(Stack *pst) //获取栈顶数据
{
	assert(pst);
	assert(!StackEmpty(pst));  //判断是否为空,为空不能取
	return pst->a[pst->top-1]; //top记录栈的顶部在哪,获取栈顶数据应从数组中取出
}

Test.c

#include "Stack.h"

int main()
{
	Stack S;
	StackInit(&S);
	StackPush(&S, 1);
	StackPush(&S, 2);
	StackPush(&S, 3);
	StackPush(&S, 4);
	while (!StackEmpty(&S))
	{
		printf("%d ", StackTop(&S)); //StackTop函数有参数,不要忘记
		StackPop(&S);
	}
	printf("\n");
	
	StackDestory(&S);
	return 0;
}

测试结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值