链式栈
环境:gcc
目的:链式栈练习
功能:
1. 创建栈
2 . 入栈
3. 出栈
/*************************************************************************
@Author: wanghao
@Created Time : Wed 09 May 2018 10:42:01 PMPDT
@File Name: linklist.c
@Description:
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
typedef int data_t;
typedef struct stack_t
{
data_t data;
struct stack_t *pnext;
}Stack;
Stack *create_stack(void)
{
Stack*node = NULL;
node = (Stack *)malloc(sizeof(Stack));
if(!node)
{
printf("Malloc node fail!\n");
return NULL;
}
node->data = 0;
node->pnext = NULL;
return node;
}
int empty_stack(Stack *stack)
{
if(!stack)
{
printf("Stackdoes not exist!\n");
return -1;
}
return stack->pnext == NULL ? 1 : 0;
}
int push_stack(Stack *stack, data_t data)
{
Stack*newnode = NULL;
if(!stack)
{
printf("Stackdoes not exist!\n");
return -1;
}
newnode = create_stack();
if(!newnode)
{
printf("Createstack fail!\n");
return 0;
}
newnode->data= data;
newnode->pnext = stack->pnext;
stack->pnext = newnode;
return 1;
}
int pop_stack(Stack *stack, data_t *data)
{
Stack *node = NULL;
if(!stack)
{
printf("Stackdoes not exist!\n");
return -1;
}
if(empty_stack(stack))
{
printf("Stackis empty!\n");
return 0;
}
node = stack->pnext;
stack->pnext= node->pnext;
*data = node->data;
free(node);
node = NULL;
return 1;
}
int main(int argc, const char *argv[])
{
int i;
data_t data;
Stack *stack = NULL;
stack = create_stack();
if(!stack)
{
printf("Createstack fail!\n");
return -1;
}
for(i= 0; i < 5; i++)
{
push_stack(stack,i+1);
}
for(i= 0; i < 6; i++)
{
pop_stack(stack,&data);
printf("%d\t",data);
}
printf("\n");
return 0;
}