栈的顺序存储结构描述
#define MaxSize 50 //定义栈中元素的最大个数
typedef struct{
ElemType data[MaxSize]; //存放栈中元素
int top; //栈顶指针
}SqStack;
初始化
//初始化
void InitStack(SqStack &S){
S.top==-1; //初始化栈顶指针
}
判栈空
//判栈空
bool StackEmpty(SqStack S){
if(S.top==-1) //栈空
return true;
else //不空
return false;
}
进栈
//进栈
bool Push(SqStack &S, ElemType x){
if(S.top==MaxSize-1) //栈满,报错
return false;
S.data[++S.top]=x; //指针先加1,再入栈
return true;
}
出栈
//出栈
bool Pop(SqStack &S, ElemType &x){
if(S.top==-1) //栈空,报错
return false;
x=S.data[S.top--]; //先出栈,指针再减1
return true;
}
读取栈顶元素
//读取栈顶元素
bool GetTop(SqStack S, ElemType x){
if(S.top==-1) //栈空,报错
return false;
x=S.data[S.top]; //x记录栈顶元素
return true;
}
若栈顶指针初始化为S.top=0,即top指向栈顶元素的下一位置,则入栈操作变为S.data[S.top++]=x;出栈操作变为x=S.data[--S.top]。栈空变为S.top==0,栈满变为S.top==MaxSize。