中国网站排名 优帮云/企业培训师
这些都是头函数里的内容,也就是保存之后,可以直接
对其进行调用。其中的一个变量stacklen是用来记录栈
的长度的,其实,这个变量可以不要,只是刚开始写时
给它加上了,所以就按这样写了,感觉跟顺序表的写法
差不多
#include<iostream>
#include<stdlib.h>
#include<malloc.h>
using namespace std;typedef int Status;
typedef int SElemType;# define OK 1
# define ERROR 0
# define TRUE 1
# define FLASE 0
# define NULL 0
# define OVERFLOW -2typedef struct{SElemType * base;SElemType * top;int stacksize;int stacklen;
}SqStack;# define STACK_INIT_SIZE 100 //存储空间的初始分配量
# define STACKINCREMENT 10 //存储空间分配增量Status InitStack(SqStack &S) //构造一个空栈S
{S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));if(!S.base) exit(OVERFLOW);S.top = S.base;S.stacksize = STACK_INIT_SIZE;S.stacklen = 0; return OK;
}Status DestroyStack(SqStack &S) //销毁栈S,S不在存在
{free(S.base);return OK;
}Status ClearStack (SqStack &S) //把S置为空栈
{S.top = S.base;S.stacklen = 0;return OK;
}Status StackEmpty(SqStack &S) //若S为空栈,则返回TRUE,否则返回FALSE
{if(S.stacklen == 0)return TRUE;elsereturn FLASE;
}Status StackLength(SqStack &S) //返回S的元素个数,即栈的长度
{return S.stacklen;
}Status GetTop(SqStack &S, SElemType &e) //若栈不空,则用e返回S的栈顶元素,
{if(S.stacklen == 0)return ERROR;else{e = * (S.top-1);return OK;}
}Status Push(SqStack &S, SElemType &e) //插入元素e为新的栈顶元素
{if(S.stacklen == S.stacksize){S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));if(!S.base) exit(OVERFLOW);S.top = S.base + S.stacksize;S.stacksize += STACKINCREMENT;}* S.top++ = e;S.stacklen++;return OK;
}Status Pop(SqStack &S, SElemType &e) //删除栈顶元素并用e返回其值
{if(S.stacklen == 0) return ERROR;e = * --S.top;S.stacklen--;return OK;
}Status DisplayStack(SqStack &S) //从栈底到栈顶依次对栈的元素进行访问
{SElemType * p;p = S.base;while(p != S.top){cout<<*p<<" ";p++;}cout<<endl;return OK;
}