#include "link_stack.h"
/*************************
创建
入栈
出栈
是否为空
获取栈顶数据
清空栈
*************************/
//创建
void creat_link_stack_1(pLinkStack *stack)
{
(*stack) = (pLinkStack)malloc(sizeof(tLinkStack));
if(NULL == (*stack))
{
printf("creat_link_stack_1 malloc err\r\n");
}
(*stack)->len = 0;
(*stack)->top = NULL;
}
//创建
void creat_link_stack_2(pLinkStack stack)
{
if(NULL == stack)
{
return;
}
stack->len = 0;
stack->top = NULL;
}
//创建
pLinkStack creat_link_stack_3(void)
{
pLinkStack stack;
stack = (pLinkStack)malloc(sizeof(tLinkStack));
if(NULL == stack)
{
printf("creat_link_stack_3 malloc err\r\n");
return NULL;
}
stack->len = 0;
stack->top = NULL;
}
//清空栈
int clear_link_stack(pLinkStack stack)
{
pStackNode free_node;
if(NULL == stack)
{
return 1;
}
while(NULL != stack->top)
{
free_node = stack->top;
stack->top = stack->top->next;
free(free_node);
}
free(stack);
return 0;
}
//是否为空
int is_empty_link_stack(pLinkStack stack)
{
if((NULL == stack) || (NULL == stack->top) || (0 == stack->len))
{
return 1;
}
return 0;
}
//获取栈顶数据
int get_top_link_stack(pLinkStack stack,STACK_DATA_TYPE *data)
{
if(is_empty_link_stack(stack))
{
return 1;
}
*data = stack->top->data;
return 0;
}
//压栈
int push_link_stack(pLinkStack stack,STACK_DATA_TYPE data)
{
pStackNode new_node;
if(is_empty_link_stack(stack))
{
return 1;
}
new_node = (pStackNode)malloc(sizeof(tStackNode));
if(NULL == new_node)
{
printf("push_link_stack malloc err\r\n");
return 1;
}
new_node->data = data;
new_node->next = stack->top;
stack->top = new_node;
stack->len++;
return 0;
}
//出栈
int pop_link_stack(pLinkStack stack,STACK_DATA_TYPE *data)
{
if(is_empty_link_stack(stack))
{
return 1;
}
*data = stack->top->data;
stack->top = stack->top->next;
stack->len--;
return 0;
}
#ifndef LINK_STACK_H_INCLUDED
#define LINK_STACK_H_INCLUDED
#ifndef NULL
#define NULL ((void *)0)
#endif // NULL
#define STACK_DATA_TYPE int
typedef struct _STACK_NODE
{
STACK_DATA_TYPE data;
struct _STACK_NODE *next;
}tStackNode,*pStackNode;
typedef struct _LINK_STACK
{
int len;
pStackNode top;
}tLinkStack,*pLinkStack;
extern void creat_link_stack_1(pLinkStack *stack);
extern void creat_link_stack_2(pLinkStack stack);
extern pLinkStack creat_link_stack_3(void);
extern int clear_link_stack(pLinkStack stack);
extern int is_empty_link_stack(pLinkStack stack);
extern int get_top_link_stack(pLinkStack stack,STACK_DATA_TYPE *data);
extern int push_link_stack(pLinkStack stack,STACK_DATA_TYPE data);
extern int pop_link_stack(pLinkStack stack,STACK_DATA_TYPE *data);
#endif // LINK_STACK_H_INCLUDED