栈的实现

main.c文件

#include"Stack.h"

int main()
{
	StackTest();
	system("pause");
	return 0;
}

Stack.h文件

#pragma once;

#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<assert.h>

//栈  --后进先出
typedef int STDataType;

typedef struct Stack
{
	STDataType *_a;//指针
	int _top;//栈顶的下一个元素
	int _capacity;//容量
}Stack;

void StackInit(Stack *ps, int n);
void StackDestory(Stack *ps);
void StackPush(Stack *ps, STDataType x);
void StackPop(Stack *ps);
STDataType StackTop(Stack *ps);
int StackSize(Stack *ps);
//空返回0,非空返回1
int StackEmpty(Stack *ps);

void StackTest();

Stack.c文件

#include"Stack.h"

void StackInit(Stack *ps, int n)
{
	assert(ps);

	ps->_a = (STDataType *)malloc(sizeof(STDataType)*n);
	//开辟空间是否成功
	assert(ps->_a);
	ps->_capacity = n;
	ps->_top = 0;
}
void StackDestory(Stack *ps)
{
	assert(ps);

	if (ps->_top)
	{
		free(ps->_a);
		ps->_a = NULL;
		ps->_top = 0;
		ps->_capacity = 0;
	}
}
void StackPush(Stack *ps, STDataType x)
{
	assert(ps);

	//判断容量是否满
	if (ps->_top == ps->_capacity)
	{
		ps->_a = realloc(ps->_a, sizeof(STDataType)*ps->_capacity * 2);
		ps->_capacity *= 2;
	}
	ps->_a[ps->_top] = x;
	ps->_top++;
}

void StackPop(Stack *ps)
{
	assert(ps);

	//判断还有没有数据可删
	if (ps->_top > 0)
	{
		ps->_top--;
	}
}

STDataType StackTop(Stack *ps)
{
	assert(ps);

	return ps->_a[ps->_top - 1];
}

int StackSize(Stack *ps)
{
	assert(ps);

	return ps->_top;
}

int StackEmpty(Stack *ps)
{
	assert(ps);

	return ps->_top == 0 ? 0 : 1;
}

void StackTest()
{
	Stack ps;
	StackInit(&ps,3);
	StackPush(&ps, 1);
	StackPush(&ps, 2);
	StackPush(&ps, 3);
	StackPush(&ps, 4);
	StackPush(&ps, 5);
	printf("Empty:%d\n", StackEmpty(&ps));
	printf("Size:%d\n", StackSize(&ps));
	/*Stack *cur = ps;
	while (cur->_top)*/
	while (ps._top)
	{
		printf("top=%d\n", StackTop(&ps));
		StackPop(&ps);
	}
	printf("Empty:%d\n", StackEmpty(&ps));
	printf("Size:%d\n", StackSize(&ps));
	StackDestory(&ps);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值