栈的实现

Stack.h

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int DATATYPE;
typedef struct Stack
{
	DATATYPE* _arr;
	int top;
	int capicity;
}Stack;

void StackInit(Stack* ps);
void StackPush(Stack* ps,DATATYPE x);
void StackPop(Stack* ps);
DATATYPE StackTop(Stack *ps);
int StackEmpty(Stack* ps);
int StackSize(Stack* ps);
void StackPrint(Stack* ps);

Stack.c

#include"Stack.h"

void StackInit(Stack* ps)
{
	assert(ps);
	ps->_arr = NULL;
	ps->top = 0;
	ps->capicity = 0;
}

void StackPush(Stack* ps, DATATYPE x)
{
	assert(ps);
	int newc = 0;
	if (ps->capicity == ps->top)
	{
		newc = (ps->capicity == 0 ? 10 : 2 * ps->capicity);
		ps->_arr = (DATATYPE*)realloc(ps->_arr,newc*sizeof(DATATYPE));
		ps->capicity = newc;
	}
	ps->_arr[ps->top++] = x;
}

void StackPop(Stack* ps)
{
	assert(ps);
	if (ps->top == 0)
	{
		return;
	}
	ps->top--;
}

DATATYPE StackTop(Stack *ps)
{
	assert(ps);
	return ps->_arr[ps->top - 1];
}

int StackEmpty(Stack* ps)
{
	assert(ps);
	return ps->top == 0 ? 0 : 1;
}

int StackSize(Stack *ps)
{
	assert(ps);
	return ps->top;
}

void StackPrint(Stack* ps)
{
	assert(ps);
	while (StackEmpty(ps) == 1)
	{
		printf("%d ", StackTop(ps));
		StackPop(ps);
	}
	printf("\n");
}
#include"Stack.h"
int main()
{
	test();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值