线性表的应用:
顺序栈的基本操作
#include<stdio.h>
#define MaxSize 10
typedef struct SqStack{
int data[MaxSize];
int top;
}SqStack;
bool InitSqStack(SqStack &S){
S.top = -1;
return true;
}
bool StackEmpty(SqStack &S){
if(S.top == -1){
return true;
}else{
return false;
}
}
bool Push(SqStack &S,int e){
if(S.top == MaxSize-1){
return false;
}
S.top = S.top+1;
S.data[S.top] = e;
return true;
}
bool Pop(SqStack &S,int &e){
if(S.top == -1){
return false;
}
e = S.data[S.top];
S.top = S.top-1;
return true;
}
void PrintSqstack(SqStack S){
for(int i=0;i<=S.top;i++){
printf("栈的第%d个元素为:%d\n",i+1,S.data[i]);
}
}
bool SqStackUpdata(SqStack &S,int e){
if(S.top == -1){
return false;
}
S.data[S.top] = e;
return true;
}
int GetElem(SqStack S){
if(S.top == -1){
return false;
}
return S.data[S.top];;
}
void Copoer(){
printf("--------------------------------------------\n");
printf("| -----1、顺序栈--初始化----- |\n");
printf("| -----2、栈数据--插入----- |\n");
printf("| -----3、栈数据--删除----- |\n");
printf("| -----4、栈数据--修改----- |\n");
printf("| -----5、栈数据--获取栈顶元素----- |\n");
printf("| -----7、栈数据--展示----- |\n");
printf("| -----0、-----退出------- |\n");
printf("|--------------------------------------------\n\n");
}
int main(){
int i,e,m=10;
SqStack S;
while (m!=0){
Copoer();
printf("请输入要操作的数字:");
scanf("%d",&m);
if(m==1){
if(InitSqStack(S)){
printf("栈初始化成功!!!!\n");
}
}
if(m==2){
printf("请输入要插入的值e:");
scanf("%d",&e);
if(Push(S,e)){
printf("数据%d插入成功\n",e);
}
}
if(m==3){
e = -1;
if(Pop(S,e)){
printf("栈元素%d数据删除成功!!!\n",e);
}
}
if(m==4){
printf("请输入要修改的元素e:");
scanf("%d",&e);
if(SqStackUpdata(S,e)){
printf("修改成功!!!\n");
}
}
if(m==5){
if(GetElem(S)){
printf("栈顶元素为:%d\n",GetElem(S));
}
}
if(m==7){
PrintSqstack(S);
}
if(m==0){
return 0;
}
}
return 0;
}
注:本程序在vscode上编译运行的,在输入数据时输入的数据之间用“,”逗号隔开。其他的编译软件输入的数据之间应该只需要敲空格。
如有任何问题,欢迎各位留言评论,谢谢!!!!