一、题目描述
二、思路
声明两个队列解决:
queue<int> q1用于存储元素;
queue<int> q2用于辅助操作。
push()方法实现:
直接将元素存入q1。
top()、pop()方法实现:
先将q1除了队尾元素外的所有元素全部存入q2;
q1只剩队尾元素,即:栈顶元素,操作;
将q2的元素依次弹出全部存入q1。
empty()方法实现:
直接检查q1是否为空即可。
三、代码
class MyStack {
public:
queue<int> q1; // 用于存储
queue<int> q2; // 用于辅助
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
while(q1.size() > 1){
int cur = q1.front();
q2.push(cur);
q1.pop();
}
// 此时q1还剩队尾元素
int res = q1.front();
q1.pop();
while(q2.size() != 0){
int cur = q2.front();
q1.push(cur);
q2.pop();
}
return res;
}
/** Get the top element. */
int top() {
while(q1.size() > 1){
int cur = q1.front();
q2.push(cur);
q1.pop();
}
// 此时q1还剩队尾元素
int res = q1.front();
q2.push(res);
q1.pop();
while(q2.size() != 0){
int cur = q2.front();
q1.push(cur);
q2.pop();
}
return res;
}
/** Returns whether the stack is empty. */
bool empty() {
if(q1.size() == 0)
return true;
return false;
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/