栈的操作是线性表操作的特例
///栈的链式表示
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <malloc.h>
using namespace std;
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int SElemType;
typedef struct node
{
SElemType data;//栈中元素的值
int stacklength;//栈中元素的数量
struct node *next;
} SNode, *SList;
//构造一个空栈S
Status InitStack(SList &S);
//销毁栈S, 栈S不再存在
Status DestroyStack(SList &S);
//把S置为空栈
Status ClearStack(SList &S);
//若S为空栈,则返回true,否则返回FALSE
Status StackEmpty(SList S);
/*获取栈顶元素,
若栈不空,则用e返回S的栈顶元素,并返回OK,
否则返回ERROR*/
Status GetTop(SList S, SElemType &e);
//插入元素e作为新的栈顶元素
Status Push(SList &S, SElemType e);
//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
Status Pop(SList &S, SElemType &e);
//读出元素
Status vi(SElemType e);
//从栈底到栈顶依次对栈中的每个元素调用函数visit(). 一旦visit()失败, 则操作失败
Status StackTraverse(SList S, Status(*visit)(SElemType));
int main()
{
SList S;
InitStack(S);
if(StackEmpty(S))
{
printf("创建栈之后, 栈为空\n");
}
for(int i = 0; i < 6; i++)
{
Push(S, i);
}
if(!StackEmpty(S))
{
printf("添加元素之后, 栈不空\n");
}
StackTraverse(S, vi);//遍历栈中元素
printf("栈的长度: %d\n", S->stacklength);
SElemType e;
GetTop(S, e);
printf("栈顶元素: %d\n", e);
Pop(S, e);
printf("删除的栈顶元素: %d\n", e);
StackTraverse(S, vi);//遍历栈中元素
ClearStack(S);
if(StackEmpty(S))
{
printf("清空栈之后, 栈为空\n");
}
DestroyStack(S);
return 0;
}
//构造一个空栈S
Status InitStack(SList &S)
{
S = (SList)malloc(sizeof(SNode));
if(!S)
{
printf("存储分配失败!\n");
return ERROR;
}
S->next = NULL;
S->stacklength = 0;
return OK;
}
//销毁栈S, 栈S不再存在
Status DestroyStack(SList &S)
{
S->stacklength = 0;//栈已销毁,空间已释放,当前栈中元素的数量为0
while(S)
{
SList e = S;
free(e);
S = S->next;
}
return OK;
}
//把S置为空栈
Status ClearStack(SList &S)
{
while(S->next)
{
SList e = S;
free(e);
S = S->next;
}
S->next = NULL;
return OK;
}
//若S为空栈,则返回true,否则返回FALSE
Status StackEmpty(SList S)
{
if(!S->next)
{
return TRUE;
}
return FALSE;
}
/*获取栈顶元素,
若栈不空,则用e返回S的栈顶元素,并返回OK,
否则返回ERROR*/
Status GetTop(SList S, SElemType &e)
{
if(!S->next)
{
return ERROR;
}
e = S->next->data;
return OK;
}
//插入元素e作为新的栈顶元素
Status Push(SList &S, SElemType e)
{
SList q = (SList)malloc(sizeof(SNode));
q->data = e;
q->next = S->next;
S->next = q;
S->stacklength++;
return OK;
}
//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
Status Pop(SList &S, SElemType &e)
{
if(!S->next)
{
return ERROR;
}
S->stacklength--;
SList q = S->next;
S = q->next;
e = q->data;
free(q);
return OK;
}
//读出元素
Status vi(SElemType e)
{
printf("%d ", e);
return OK;
}
//从栈底到栈顶依次对栈中的每个元素调用函数visit(). 一旦visit()失败, 则操作失败
Status StackTraverse(SList S, Status(*visit)(SElemType))
{
SElemType e;
printf("遍历栈中元素: ");
SList p = S->next;
while(p)
{
e = p->data;
p = p->next;
if(!(*visit)(e))
{
return ERROR;
}
}
printf("\n");
return OK;
}