head.h
#include<io.h> /* eof() */
#include<math.h> /* floor(),ceil(),abs() */
#include<process.h> /* exit() */
/* 函数结果状态代码 */
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
/* #define OVERFLOW -2 因为在math.h中已定义OVERFLOW的值为3,故去掉此行 */
typedef int Status; /* Status是函数的类型,其值是函数结果状态代码,如OK等 */
typedef int Boolean; /* Boolean是布尔类型,其值是TRUE或FALSE */
typedef int SElemType;
typedef struct StackNode {
SElemType data;
struct StackNode *next;
}StackNode,*StackNodePosition;
typedef struct LinkStack
{
StackNodePosition top;
int count;
}LinkStack,*PLinkStack;
LinkStack *InitStack(); //构造一个空栈S
Status Destroy(LinkStack *S); //销毁栈S
Status ClearStack(LinkStack *S); //将S清为空栈
Status StackEmpty(LinkStack S); //若栈S为空,则返回TRUE,否则返回FALSE
Status StackLength(LinkStack S); //返回S的元素个数,既栈S的长度
Status GetTop(LinkStack S, SElemType *e); //用e返回S的栈顶元素
Status Push(LinkStack *S, SElemType e); //插入元素e为新的栈顶元素
Status Pop(LinkStack *S, SElemType *e); //删除S的栈顶元素并用e返回其值
void StackTraverse(LinkStack S); //从栈底一次输出S中的各个元素数据
FunctionOperate.c
#include "LinkListStack.h"
LinkStack *InitStack() //构造一个空栈S
{
LinkStack *S;
S = (PLinkStack)malloc(sizeof(LinkStack));
if (S == NULL)
return ERROR;
S->top = NULL;
S->count = 0;
return S;
}
Status Push(LinkStack *S, SElemType e) //插入元素e为新的栈顶元素
{
StackNode *newspace;
newspace = (StackNode*)malloc(sizeof(StackNode));
if (newspace == NULL)
{
return ERROR;
}
newspace->data = e;
newspace->next = S->top;
S->top = newspace;
S->count++;
return OK;
}
Status Destroy(LinkStack *S) //销毁栈S
{
StackNode *p = S->top;
p = p->next;
while (p != NULL)
{
free(S->top);
S->top = p;
p = p->next;
}
free(S->top);
S->count = NULL;
return OK;
}
Status ClearStack(LinkStack *S) //将S清为空栈
{
StackNode *p = S->top;
p = p->next;
while (p != NULL)
{
free(S->top);
S->top = p;
p = p->next;
}
S->count = 0;
}
Status StackEmpty(LinkStack S) //若栈S为空,则返回TRUE,否则返回FALSE
{
if (S.count == 0 || !S.top)
return TRUE;
else
return FALSE;
}
Status StackLength(LinkStack S) //返回S的元素个数,既栈S的长度
{
return S.count;
}
Status GetTop(LinkStack S, SElemType *e) //用e返回S的栈顶元素
{
if (S.top==NULL)
return ERROR;
*e = S.top->data;
return OK;
}
Status Pop(LinkStack *S, SElemType *e) //删除S的栈顶元素并用e返回其值
{
StackNode *p;
if (S->top == NULL)
return ERROR;
*e = S->top->data;
p = S->top;
S->top = S->top->next;
S->count--;
free(p);
return OK;
}
void StackTraverse(LinkStack S)
{
if (S.top == NULL)
return ERROR;
while (S.top != NULL)
{
printf(" %d ",S.top->data);
S.top = S.top->next;
}
}