采用两个队列。
- push:首先找到空的队列,将元素入栈,并将另一个队列的所有的元素依次入当前队列并清栈。保证后进先出
- pop: 找到非空的那个队列,弹出一个元素
- top: 找到非空的那个队列,top拿出一个元素
- empty: 判断两个队列是否都是非空。
关键是push操作的理解。
/**
* @author johnsondu
* @problem Implement Stack using Queues
* @url https://leetcode.com/problems/implement-stack-using-queues/
* @timeComlexity O(n^2)
* @spaceComplexity O(n)
* @strategy See code.
*/
class Stack {
public:
queue<int> q1;
queue<int> q2;
// Push element x onto stack.
void push(int x) {
if(q1.empty()) {
q1.push(x);
while(!q2.empty()) {
q1.push(q2.front());
q2.pop();
}
}
else {
q2.push(x);
while(!q1.empty()) {
q2.push(q1.front());
q1.pop();
}
}
}
// Removes the element on top of the stack.
void pop() {
if(!q1.empty()) {
q1.pop();
}
else {
if(!q2.empty()) q2.pop();
}
}
// Get the top element.
int top() {
if(!q1.empty()) {
return q1.front();
}
else {
return q2.front();
}
}
// Return whether the stack is empty.
bool empty() {
return (q1.empty() && q2.empty());
}
};