静态栈抽象数据类型stack实现

#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>

#define MAX_STACK_SIZE 10 //堆栈的最大大小

typedef struct
{
	int key;
	//其他内容
}Element;
//模板类型


void push( Element item, Element *stack, short *top);
//向堆栈压入,入栈.成功返回1失败返回0
Element pop( Element *stack, short *top);
//堆栈的弹出,出栈.成功返回被弹出的数据.失败报错
bool IsEmpty( short top);
//检查堆栈是否为空,空返回1,不空返回0
bool IsFull( short top);
//检查堆栈是否满了,满返回1,未满返回0
void stackEmpty(void);
//报告堆栈未空
void stackFull(void);
//报告堆栈已满

int main(void)
{
	Element A;
	A.key=1;
	Element stack[MAX_STACK_SIZE];
	short top=-1;
    //指向栈顶元素,-1表示空栈
    
    for(int i=0; i<MAX_STACK_SIZE; i++)
	{
		push(A, stack, &top);
		A.key+=1;
		//将A压入stack
		printf("%d ",stack[top].key);
	}
	putchar('\n');
	for(int i=0; i<MAX_STACK_SIZE; i++)
	{
		printf("%d ",pop(stack, &top).key);
		//stack出栈从栈顶开始
	}
	putchar('\n');
    
	return 0;
}
void push( Element item, Element *stack, short *top)
{
	//将item压入stack堆栈
	if(IsFull(*top))
		stackFull();
	stack[++(*top)] = item;
}
Element pop( Element *stack, short *top)
{
	if(IsEmpty(*top))
		stackEmpty();
	return stack[(*top)--];
}
bool IsEmpty( short top)
{
	if(top == -1)
		return true;
	else
		return false;
}
bool IsFull( short top)
{
	if(top == MAX_STACK_SIZE-1)
		return true;
	else
	    return false;
}
void stackEmpty(void)
{
	printf("Stack is Empty, cannot pop element\n");
	exit(EXIT_FAILURE);
}
void stackFull(void)
{
	printf("Stack is Full, cannot add element\n");
	exit(EXIT_FAILURE);
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值