兩個佇列實現一個棧,可以連續出棧,入棧時調整好順序 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;
}
}
}