leetcode - 225. 用队列实现栈
题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/45b4c2d955314854b3c1925d15a3828b.png)
代码
#include <iostream>
#include <queue>
using namespace std;
queue<int> q1;
queue<int> q2;
MyStack() {
}
void push(int x) {
if(!q1.empty()){
q1.push(x);
}else{
q2.push(x);
}
}
int pop() {
int x;
if(q1.empty()){
while(q2.size() > 1){
q1.push(q2.front());
q2.pop();
}
x = q2.front();
q2.pop();
}else{
while(q1.size() > 1){
q2.push(q1.front());
q1.pop();
}
x = q1.front();
q1.pop();
}
return x;
}
int top() {
int x;
if(q1.empty()){
while(q2.size() > 1){
q1.push(q2.front());
q2.pop();
}
x = q2.front();
q2.pop();
q1.push(x);
}else{
while(q1.size() > 1){
q2.push(q1.front());
q1.pop();
}
x = q1.front();
q1.pop();
q2.push(x);
}
return x;
}
bool empty() {
return q1.empty() && q2.empty();
}