两个队列实现一个栈,可以连续出栈,入栈时调整好顺序 C++
作者:互联网
#include<iostream>
#include<queue>
using namespace std;
struct stack{
queue<int> que1;
queue<int> que2;
static int STACK_EMPTY;
void push_stack(int val);
void pop_stack();
int top();
bool empty();
};
int stack::STACK_EMPTY = 100000;
void stack:: push_stack(int val){
que1.push(val);
int size = que2.size();
int old_val;
while(size--){
old_val = que2.front();
que2.pop();
que1.push(old_val);
}
que1.swap(que2);
return;
}
void stack::pop_stack(){
if(!que2.empty()) que2.pop();
return;
}
int stack::top(){
if(!que2.empty()) return que2.front();
return STACK_EMPTY;
}
bool stack::empty(){
if(que2.empty()) return true;
return false;
}
int main()
{
stack st;
int opt,val;
cout<<"入栈:1,出栈:2, 查看栈:3, 结束:0" << endl;
while(cin>>opt){
if(opt==1) {
cout<<"入栈:";
cin>>val;
st.push_stack(val);
}
if(opt==2) {
cout<<"出栈元素:"<<st.top()<<endl;
st.pop_stack();
}
if(opt==3){
cout<<"栈的所有元素:";
while(!st.empty()) {
cout<<st.top();
st.pop_stack();
}
}
if(opt==0) {
break;
}
}
}
标签:出栈,入栈,val,int,C++,que2,pop,return,stack 来源: https://www.cnblogs.com/daniel123/p/16347983.html