#include <stdio.h>
#include <stdlib.h>
#define MAX 10
enum return_val {FULL_OK, FULL_NO, EMPTY_OK, EMPTY_NO, PUSH_OK, PUSH_NO, POP_OK, POP_NO, GET_OK, GET_NO};
struct stack_data
{
int stack_array[MAX];
int top;
};
typedef struct stack_data Stack;
void create_stack(Stack ** stack)
{
*stack = (Stack*)malloc(sizeof(Stack));
if(*stack == NULL)
{
printf("malloc error!\n");
exit(-1);
}
}
void init_stack(Stack *stack)
{
stack->top = -1;
}
int push_stack(Stack *stack,int num)
{
if(is_full(stack) == FULL_OK)
{
printf("stack is full!\n");
//free(stack);
//exit(-1);
return PUSH_NO;
}
else
{
stack->top++;
stack->stack_array[stack->top] = num;
return PUSH_OK;
}
}
int is_full(Stack * stack)
{
if(stack->top == MAX - 1)
{
return FULL_OK;
}
else
{
return FULL_NO;
}
}
int pop_stack(Stack * stack,int *num)
{
if(is_empty(stack) == EMPTY_OK)
{
printf("stack is empty!\n");
return POP_NO;
}
else
{
*num = stack->stack_array[stack->top--];
return POP_OK;
}
}
int is_empty(Stack * stack)
{
if(stack->top == -1)
{
return EMPTY_OK;
}
else
{
return EMPTY_NO;
}
}
int gettop_stack(Stack *stack,int *num)
{
if(is_empty(stack) == EMPTY_OK)
{
printf("stack is empty!\n");
return GET_NO;
}
else
{
*num = stack->stack_array[stack->top];
return GET_OK;
}
}
void empty_stack(Stack *stack)
{
stack->top = -1;
}
int main()
{
Stack * stack;
int i;
int num;
create_stack(&stack);
init_stack(stack);
for(i = 0; i < MAX + 2; i++)
{
if(push_stack(stack,i + 1) == PUSH_OK)
{
printf("push ok!num is %d\n",i + 1);
}
else
{
printf("push no!\n");
}
}
for(i = 0; i < MAX - 2; i++)
{
if(pop_stack(stack,&num) == POP_NO)
{
printf("pop no!\n");
}
else
{
printf("stack is %d\n",num);
}
}
empty_stack(stack); //加上和去掉分别看看
for(i = 0; i < 3; i++)
{
if(gettop_stack(stack,&num) == GET_NO)
{
printf("top is empty!\n");
}
else
{
printf("top is %d\n",num);
pop_stack(stack,&num);
}
}
return 0;
}