链栈的相关操作
#include "LinkStack.h"
int StackInit(Stack **s)
{
if (NULL == s)
{
return FAILURE;
}
(*s) = (Stack *)malloc(sizeof(Stack) * 1);
if (NULL == (*s))
{
return FAILURE;
}
(*s)->top = NULL;
(*s)->count = 0;
return SUCCESS;
}
int StackEmpty(Stack *s)
{
if (NULL == s)
{
return FAILURE;
}
return (s->top == NULL) ? TRUE : FALSE;
}
int push(Stack **s, ElemType e)
{
if (NULL == s || (*s) == NULL)
{
return FAILURE;
}
Node *p = (Node *)malloc(sizeof(Node)); //给结点分配空间
if (NULL == p)
{
return FAILURE;
}
p->data = e; //数据域
p->next = (*s)->top;
(*s)->top = p;
(*s)->count++;
return SUCCESS;
}
int GetTop(Stack *s)
{
if (NULL == s || s->top == NULL)
{
return FAILURE;
}
return s->top->data;
}
int pop(Stack **s)
{
if (NULL == s || NULL == *s)
{
return FAILURE;
}
Node *p = (*s)->top;
ElemType e = (*s)->top->data;
(*s)->top = (*s)->top->next;
(*s)->count--;
free(p);
return e;
}
int StackClear(Stack **s)
{
if (NULL == s || NULL == *s)
{
return FAILURE;
}
Node *p = (*s)->top;
while (p)
{
(*s)->top = p->next;
free(p);
p = (*s)->top;
(*s)->count--;
}
return SUCCESS;
}
int StackDestroy(Stack **s)
{
if (NULL == s || NULL == *s)
{
return FAILURE;
}
free(*s);
(*s) = NULL;
return SUCCESS;
}
在此程序中,定义了两个结构体,用于分别保存结点的信息(指针、数据)和栈的信息(栈顶指针、栈中的元素个数),在链栈中一般不需要头结点。top指针总是指向栈顶元素。相关结构体声明如下:
typedef int ElemType;
//结点的信息
struct node
{
ElemType data; //数据域
struct node *next; //指针域
};
typedef struct node Node;
//栈的信息
struct stack
{
Node *top; //头指针
int count; //结点个数
};
typedef struct stack Stack;