Question
Implement the following operations of a stack using queues.
• push(x) – Push element x onto stack.
• pop() – Removes the element on top of the stack.
• top() – Get the top element.
• empty() – Return whether the stack is empty.
Notes:
• You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
• Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue – which means only push to back, pop from front, size, and is empty operations are valid.
解法1:适合push操作少而pop和top操作多的情况。
一道经典题。记得主要操作是在push()。任何时候只会有一个queue为非空。
class Stack {
public:
/*
* @param x: An integer
* @return: nothing
*/
void push(int x) {
if (q1.empty()) {
q1.push(x);
while(!q2.empty()) {
int entry = q2.front();
q1.push(entry);
q2.pop();
}
return;
}
if (q2.empty()) {
q2.push(x);
while(!q1.empty()) {
int entry = q1.front();
q2.push(entry);
q1.pop();
}
return;
}
}
/*
* @return: nothing
*/
void pop() {
if (!q1.empty()) {
q1.pop();
return;
}
if (!q2.empty()) {
q2.pop();
return;
}
}
/*
* @return: An integer
*/
int top() {
if (!q1.empty()) {
return q1.front();
}
if (!q2.empty()) {
return q2.front();
}
}
/*
* @return: True if the stack is empty
*/
bool isEmpty() {
return q1.empty() && q2.empty();
}
private:
queue<int> q1;
queue<int> q2;
};
代码同步在
https://github.com/luqian2017/Algorithm
解法2:
下面这个解法是适合push和top操作少而pop操作多的情况。push()和top()都是O(1),pop()是O(n)。
class Stack {
public:
/*
* @param x: An integer
* @return: nothing
*/
void push(int x) {
if (q1_in_use) q1.push(x);
else q2.push(x);
}
/*
* @return: nothing
*/
void pop() {
if (q1_in_use) {
while (q1.size() > 1) {
q2.push(q1.front());
q1.pop();
}
q1.pop();
} else {
while (q2.size() > 1) {
q1.push(q2.front());
q2.pop();
}
q2.pop();
}
q1_in_use = !q1_in_use;
}
/*
* @return: An integer
*/
int top() {
if (q1_in_use) return q1.back();
return q2.back();
}
/*
* @return: True if the stack is empty
*/
bool isEmpty() {
return q1.empty() && q2.empty();
}
private:
queue<int> q1, q2;
bool q1_in_use = true;
};
注意这里pop的时间复杂度为O(n)。这题跟LintCode-40: Implement Queue by Two Stacks那题不一样。那题里面的push(),pop()和top()的时间复杂度平均都是O(1),因为每个元素平均也就进q1和q2,出q1和q2一次,所以一均摊时间复杂度就是O(1)。
本文介绍两种使用队列实现栈的方法。一种适用于push操作较少的情况,另一种则在pop操作频繁时更为高效。每种方法都详细解释了如何通过两个队列来模拟栈的基本操作:push、pop、top和empty。

被折叠的 条评论
为什么被折叠?



