苦苦思索怎么用两个队列实现栈,越想越复杂,越想越懵逼,然后发现解决区的大神一个队列就搞定了【幽灵幽灵飘】
可能是模拟队列是用两个栈实现的,然后导致潜意识觉得实现栈也需要用两个队列吧。思维固化orzzzzz
class MyStack {
public:
queue<int> q;
/** Push element x onto stack. */
void push(int x) {
int length = q.size();
q.push(x);
for (int i = 0; i < length; ++i) {
q.push(q.front());
q.pop();
}
return;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int ans = q.front();
q.pop();
return ans;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
/**
* 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();
*/