#ifndef STACK_
#define STACK_
#include "stdbool.h"
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct stack_node_ {
ElementType date;
struct stack_node_ *next;
}stack_node;
typedef struct stack_ {
stack_node *top;
stack_node *bottom;
}stack;
bool init_stack(stack *st); //初始化栈
bool push(stack *st, int val);//进栈
bool pop(stack *st, int *val);//出栈
bool isEmpty(stack *st);
void display(stack *st);
#endif
#include "common.h"
#include "stack.h"
bool init_stack(stack *st)
{
st->top = (stack_node *)malloc(sizeof(stack_node));
st->bottom = (stack_node *)malloc(sizeof(stack_node));
if(NULL == st->top || NULL == st->bottom) {
perror("malloc failed.");
return false;
}
st->bottom = st->top;
st->top->next = NULL;
return true;
}
bool isEmpty(stack *st)
{
if(NULL == st) {
perror("stack is NULL");
exit(-1);
}
if(st->top == st->bottom) {
printf("stack is empty...\n");
return true;
}
return false;
}
bool push(stack *st, int val)
{
stack_node *node = (stack_node *)malloc(sizeof(stack_node));
if(NULL == node) {
perror("maolloc failed.");
return false;
}
node->date = val;
node->next = st->top;
st->top = node;
return true;
}
bool pop(stack *st, int *val)
{
if (isEmpty(st)) {
printf("Don't have date in stack.\n");
return false;
}
stack_node *tmp = st->top;
*val = tmp->date;
st->top = tmp->next;
free(tmp); //释放弹出数据内存
tmp = NULL;
return true;
}
void display(stack *st)
{
if (NULL == st) {
perror("stack is NULL.");
exit(1);
}
stack_node *tmp = st->top;
while(tmp != st->bottom) {
printf("---> %d\n", tmp->date);
tmp = tmp->next;
}
}
int main()
{
stack st;
int val;
init_stack(&st);
printf("whether stack is empty %d\n", isEmpty(&st));
push(&st, 10);
push(&st, 20);
pop(&st, &val);
printf("val --> %d\n", val);
display(&st);
return 0;
}