#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
/**定义一个顺序栈*/
typedef struct {
int data[MAXSIZE];
int top;
}SqStack;
/**初始化栈*/
void initStack(SqStack &st){
st.top=-1;
printf("初始化成功");
}
/**判断栈是否为空*/
int isEmpty(SqStack st){
if(st.top==-1){
return 1;
}
else{
return 0;
}
}
/**判断栈是否满*/
int isFull(SqStack st){
if(st.top==MAXSIZE-1){
return 1;
}
else{
return 0;
}
}
/**入栈操作*/
void push(SqStack &st,int x){
//非满状态
if(isFull(st)==0){
//入栈
st.data[++st.top]=x;
}else{
printf("栈满,请勿插入!");
}
}
/**出栈操作*/
void pop(SqStack &st,int &x){
//栈空
if(isEmpty(st)==0){
x=st.data[st.top--];
printf("%d ",x);
}else{
printf("栈空,请勿移除元素!");
}
}
/**打印栈内元素*/
void printStack(SqStack st){
for(int i=0;i<=st.top;i++){
printf("%d ",st.data[i]);
}
}
/**
主函数
*/
int main(){
SqStack st;
initStack(st);
push(st,6);
push(st,2);
push(st,5);
printf("\n");
printf("初始化栈内元素为:");
printStack(st);
printf("\n");
printf("出栈元素是:");
int x=0;
pop(st,x);
pop(st,x);
printf("\n");
printf("剩余元素:");
printStack(st);
}
顺序栈C++(考研数据结构)
最新推荐文章于 2023-06-02 00:09:21 发布