头文件
#ifndef __LINKSTACK_H__
#define __LINKSTACK_H__
#include "error.h"
#define FALSE 0
#define TRUE 1
typedef int stack_data;
typedef struct stack_node
{
stack_data data;
struct stack_node *link;
}STACKNODE;
typedef struct
{
STACKNODE *top;
}LINKSTACK;
//创建链表栈
LINKSTACK * Create_Stack();
//判断是否空战
int StackEmpty(LINKSTACK * s);
//入栈
int Push(LINKSTACK * s,stack_data x);
//出栈
int Pop(LINKSTACK * s,stack_data *x);
//获取栈顶元素
int GetTop(LINKSTACK * s,stack_data *x);
// 销毁栈
int DelStack(LINKSTACK * s);
#endif
实现函数
#include<stdio.h>
#include<stdlib.h>
#include"LinkStack.h"
#include"error.h"
//创建链表栈
LINKSTACK * Create_Stack()
{
LINKSTACK * s = (LINKSTACK *)malloc(sizeof(LINKSTACK)/sizeof(char));
if (s == NULL)
{
errno = MALLOC_ERROR;
return NULL;
}
return s;
}
//判断是否空栈
int StackEmpty(LINKSTACK * s)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
return s->top == NULL;
}
//入栈
int Push(LINKSTACK * s,stack_data x)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
STACKNODE *node = (STACKNODE *)malloc(sizeof(STACKNODE)/sizeof(char));
if (node == NULL)
{
errno = MALLOC_ERROR;
return FALSE;
}
node->data = x;
node->link = s->top;
s->top = node;
return TRUE;
}
//出栈
int Pop(LINKSTACK * s,stack_data *x)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
if (StackEmpty(s))
{
errno = EMPTY;
return FALSE;
}
*x = s->top->data;
STACKNODE *p = s->top;
s->top = p->link;
free(p);
return TRUE;
}
//获取栈顶元素
int GetTop(LINKSTACK * s,stack_data *x)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
*x = s->top->data;
return TRUE;
}
// 销毁栈
int DelStack(LINKSTACK *s)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
//不用判断栈空
stack_data x;
while(StackEmpty(s) != TRUE)
{
Pop(s,&x);
}
free(s);
return TRUE;
}