题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
#include <ostream>
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
int temp = stack2.top();
stack2.pop();
// cout << stack2.top() << endl;
while (!stack2.empty()) {
stack1.push(stack2.top());
stack2.pop();
}
return temp;
}
private:
stack<int> stack1;
stack<int> stack2;
};
栈是先进后出,队列是先进先出,要使用栈来实现队列,push的时候直接push进入一个栈中,pop的时候要满足先入先出则需要输出栈底的值,所以要把栈中所有的值都pop到栈2中,再top出栈顶值,最后再把栈2剩余的数据pop并push到栈1中。

查看8道真题和解析