基础知识
栈(stack):只允许在一端进行插入或删除操作的线性表,先进后出(FILO)
栈底是a1,栈顶是an(top);
顺序栈SqStack:定义,入栈,出栈,栈空栈满,获取栈顶元素
顺序栈练习:
1. 定义与初始化
#define MaxSize 5
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top;//始终指向栈顶的变量
}SqStack;
//初始化栈
void InitStack(SqStack &s){
s.top=-1;//即栈为空
}
2. 判断栈是否为空
//判断栈是否为空
bool StackEmpty(SqStack s){
if(-1 == s.top){
return true;
}else{
return false;
}
}
3. 入栈
//入栈
bool Push(SqStack &s,ElemType elem){
//判断栈是否满了
if(s.top == MaxSize-1){
return false;
}
s.data[++s.top]=elem;//等价于s.top=s.top+1; s.data[s.top]=x;
return true;
}
4. 获取栈顶元素
//获取栈顶元素
bool GetTop(SqStack s,ElemType &e){
if(StackEmpty(s)){
return false;
}
e=s.data[s.top];//拿栈顶元素
return true;
}
5. 出栈
//弹栈
bool Pop(SqStack &s,ElemType &elem){
if(StackEmpty(s)){
return false;
}
elem=s.data[s.top--];//出栈,等价于elem=s.data[s.top]; s.top--;
return true;
}
6. 主函数
int main() {
SqStack S;
InitStack(S);//初始化栈
bool flag;
flag = StackEmpty(S);//判断栈是否为空
if(flag){
printf("stack is empty\n");
}
printf("----------------------\n");
ElemType e1,m,element;
printf("input stack:\n");
for(int i=0;i<3;i++) {//入栈,e1为每次入栈的元素
scanf("%d",&e1);
Push(S,e1);
}
flag = GetTop(S,m);//获取栈顶元素
if(flag){
printf("get top %d\n",m);
}
printf("----------------------\n");
printf("pop stack:\n");
while(S.top>=0) {//依次弹出栈顶元素,打印
Pop(S, element);
printf("%2d",element);
}
printf("\n");
printf("----------------------\n");
return 0;
}