//顺序栈的基本操作
#include <iostream>
#define MAXSIZE 16
using namespace std;
typedef int elementype;
typedef struct{
elementype* pbase;
elementype top;
}Stack;
bool initStack(Stack &Q);//初始化栈
bool creatstack(Stack &Q);//建栈
bool isEmpty(Stack &Q);//判断栈是否为空
bool isFull(Stack &Q);//判断栈是否为满
bool pushstack(Stack &Q,int e);//压栈
bool popstack1(Stack &Q);//出栈
int popstack2(Stack &Q);//出栈,并返回栈顶元素
void traverstack(Stack &Q);//遍历栈
int main(){
Stack m;
bool a = initStack(m);
if(a)
cout << "初始化栈成功" << endl;
a = creatstack(m);
if(a)
cout << "建栈成功" << endl;
cout << "请输入要压入栈的元素值" << endl;
int n;
cin >> n;
a = pushstack(m,n);
if(a)
cout << "压栈成功" << endl;
traverstack(m);
a = popstack1(m);
if(a)
cout << "出栈成功" << endl;
traverstack(m);
elementype q = popstack2(m);
cout << "出栈成功,栈顶元素是" << q << endl;
traverstack(m);
return 0;
}
//初始化栈
bool initStack(Stack &Q){
Q.pbase = new elementype[MAXSIZE];
Q.top = -1;
return true;
}
//建栈
bool creatstack(Stack &Q){
int i = 0;
cout << "请输入要输入的元素值个数" << endl;
cin >> i;
cout << "请输入要输入的元素值" << endl;
for(int j=0;j<i;j++){
int n;
cin >> n;
pushstack(Q,n);
}
return true;
}
//压栈
bool pushstack(Stack &Q,int e){
if(isFull(Q)){
cout << "栈已满,不能继续压栈" << endl;
exit(-1);
}
Q.top++;
Q.pbase[Q.top] = e;
return true;
}
//出栈
bool popstack1(Stack &Q){
if(isEmpty(Q)){
cout << "栈已空,不能" << endl;
exit(-1);
}
Q.top--;
return true;
}
//出栈,并返回栈顶元素
int popstack2(Stack &Q){
if(isEmpty(Q)){
cout << "栈已空,不能遍历" << endl;
exit(-1);
}
elementype e = Q.pbase[Q.top];
Q.top--;
return e;
}
//判断栈是否为满
bool isFull(Stack &Q){
if(Q.top == MAXSIZE - 1)
return true;
return false;
}
//判断栈是否为空
bool isEmpty(Stack &Q){
if(Q.top == -1)
return true;
return false;
}
//遍历栈
void traverstack(Stack &Q){
if(isEmpty(Q)){
cout << "栈已空,不能遍历" << endl;
exit(-1);
}
cout << "此时栈中的元素是" << endl;
elementype n = Q.top;
while(n != -1){
cout << Q.pbase[n--] << " ";
}
cout << endl;
}
顺序栈的基本操作
最新推荐文章于 2024-01-23 21:08:19 发布