用两个栈实现队列(五)

题目描述:

用两个栈来实现一个队列,完成队列的 ​​Push​​​ 和 ​​Pop​​​ 操作。 队列中的元素为 ​​int​​ 类型。

代码(已在牛客上 AC)

使用两个栈, 将新来的元素总插入 ​​s1​​​ 中, 然后当要 ​​pop​​​ 时, 先判断 ​​s2​​​ 中是否为空, 如果为空, 那么就将 ​​s1​​​ 中的元素全都丢进 ​​s2​​​ 中, 否则直接弹出 ​​s2​​ 栈顶的元素.

另一道镜像的题目: 使用队列实现栈, 在 LeetCode 上有原题, 可以做做看. 那道题就不要定式思维, 觉得是不是要用两个队列实现栈啊… No! Naive, 使用一个队列就可以实现栈了.

class Solution
{
public:
void push(int node) {
stack1.push(node);
}

int pop() {
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
int res = stack2.top();
stack2.pop();
return res;
}

private:
stack<int> stack1;
stack<int> stack2;
};