目录
1.顺序栈类型定义
typedef struct {
int elem[MAXSIZE];
int top;
}SqStack;
2.初始化顺序栈
void InitStack(SqStack &S){ //初始化
S.top=0; //代表栈空
}
3.入栈
bool Push(SqStack &S,int x){ //入栈
if(S.top>=MAXSIZE)
return false;
S.elem[++S.top]=x;
return true;
}
4.出栈
bool Pop(SqStack &S,int &x){ //出栈
if(S.top==0)
return false;
x=S.elem[S.top--];
return true;
}
5.遍历输出栈内所有元素
void PrintStack(SqStack S){ //遍历
for(int i=S.top;i>0;i--)
printf("%3d",S.elem[i]);
printf("\n");
}
6.查看栈顶元素
bool Top(SqStack S,int &x){ //查看栈顶元素
if(S.top==0)
return false;
x=S.elem[S.top];
return true;
}
7.完整代码
#include <stdio.h>
#define MAXSIZE 50
typedef struct {
int elem[MAXSIZE];
int top;
}SqStack;
void InitStack(SqStack &S){ //初始化
S.top=0; //代表栈空
}
bool Push(SqStack &S,int x){ //入栈
if(S.top>=MAXSIZE)
return false;
S.elem[++S.top]=x;
return true;
}
bool Pop(SqStack &S,int &x){ //出栈
if(S.top==0)
return false;
x=S.elem[S.top--];
return true;
}
void PrintStack(SqStack S){ //遍历
for(int i=S.top;i>0;i--)
printf("%3d",S.elem[i]);
printf("\n");
}
bool Top(SqStack S,int &x){ //查看栈顶元素
if(S.top==0)
return false;
x=S.elem[S.top];
return true;
}
int main(){
SqStack S;
int x;
InitStack(S);
for(;;){
scanf("%d",&x);
if(x==-1)
break;
Push(S,x);
}
PrintStack(S);
Pop(S,x);
printf("出栈元素:%d\n",x);
PrintStack(S);
Top(S,x);
printf("栈顶元素:%d\n",x);
return 0;
}