#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);
}
静态栈抽象数据类型stack实现
最新推荐文章于 2024-01-26 14:00:19 发布