环境:gcc
目的:顺序栈练习
功能:
1. 创建栈
2 . 入栈
3. 出栈
/*************************************************************************
@Author: wanghao
@Created Time : Wed 09 May 2018 08:29:13 PMPDT
@File Name: stack.c
@Description:
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef int data_t;
typedef struct stack_t
{
data_t data[MAXSIZE];
int top;
}Stack;
Stack *create_stack(void)
{
Stack* stack = NULL;
stack = (Stack *)malloc(sizeof(Stack));
if(stack == NULL)
{
printf("Mallocstack fail!\n");
return NULL;
}
stack->top = -1;
return stack;
}
int empty_stack(Stack *stack)
{
if(!stack)
{
printf("Thestack does not exist!\n");
return-1;
}
returnstack->top == -1 ? 1 : 0;
}
int full_stack(Stack *stack)
{
if(!stack)
{
printf("Thestack does not exist!\n");
return-1;
}
return stack->top == MAXSIZE-1 ? 1 : 0;
}
int push_stack(Stack *stack, data_t data)
{
if(!stack)
{
printf("Thestack does not exist!\n");
return-1;
}
if(full_stack(stack))
{
printf("Thestack is full!\n");
return0;
}
stack->top++;
stack->data[stack->top]= data;
}
int pop_stack(Stack *stack, data_t *data)
{
if(!stack)
{
printf("Thestack does not exist!\n");
return-1;
}
if(empty_stack(stack))
{
printf("Thestack is empty!\n");
return0;
}
*data= stack->data[stack->top];
stack->top--;
}
int main(int argc, const char *argv[])
{
int i;
data_tdata;
Stack* stack = NULL;
stack= create_stack();
if(!stack)
{
printf("Createstack fail!\n");
return-1;
}
for(i= 0; i <= MAXSIZE; i++)
{
push_stack(stack,i);
}
for(i= 0; i <= MAXSIZE; i++)
{
pop_stack(stack,&data);
printf("%d\t",data);
}
printf("\n");
return 0;
}