顺序栈的初始化,元素入栈,出站,查找栈顶元素。
#include <iostream>
using namespace std;
#define MaxSize 5
struct SqStack{
int data[MaxSize];
int top;
};
void InitStack(SqStack &S){
S.top=-1;
}//初始化栈
bool Push(SqStack &S,int x){
if(S.top==MaxSize-1)
return false;
S.top=S.top+1;//++S.top
S.data[S.top]=x;
return true;
}//将x入栈
bool GetTop(SqStack &S,int &x){
if(S.top==-1){
return false;
}
x=S.data[S.top];
return true;
}//查询栈顶元素
bool Pop(SqStack &S,int &x){
if(S.top==-1)
return false;
x=S.data[S.top--];
return true;
}//删除栈顶元素
int main(void){
SqStack S;
InitStack(S);
int i=1;
while(Push(S,i)){
i++;
}//将1-5入栈;
for(i=0;i<S.top+1;i++){
cout<<S.data[i]<<" ";
}//打印栈中元素
cout<<endl;
int x=0;
Pop(S,x);
cout<<x<<endl;
GetTop(S,x);
cout<<x<<endl;
}