数组实现栈
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1000
#define element_type int
typedef struct
{
element_type data[MAXSIZE];
int top;
}Stack;
/*初始化栈*/
Stack * init_stack()
{
Stack * stack;
stack = (Stack*)malloc(sizeof(element_type)*MAXSIZE);
stack->top = -1;
return stack;
}
/*判断栈是否为空*/
int is_empty(Stack *stack)
{
if(stack->top==-1){
printf("栈空");
return 1;
}
return 0;
}
/*是否满栈*/
int is_full(Stack *stack)
{
if(stack->top==MAXSIZE-1){
printf("栈满");
return 1;
}
return 0;
}
/*压栈*/
void push(Stack * stack,element_type elem)
{
if(!is_full(stack)){
stack->data[++stack->top] = elem;
}
}
/*弹栈*/
element_type pop(Stack *stack)
{
if(is_empty(stack)){
return -1;
}
return stack->data[stack->top--];
}
/*打印当前栈中所有元素*/
void print_stack(Stack * stack)
{
for(int i=stack->top;i>=0;i--){
printf("%d ",stack->data[i]);
}
}
int main()
{
Stack *stack;
stack = init_stack();
push(stack,1);
push(stack,2);
push(stack,3);
push(stack,4);
push(stack,5);
printf("%d ",pop(stack));
printf("%d \n",pop(stack));
print_stack(stack);
return 0;
}