用两个栈实现队列,c++
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
// out栈清空
while (!stack2.empty())
stack2.pop();
// in栈倒入
while (!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
int res = stack2.top();
stack2.pop();
// out倒入in
while (!stack2.empty()){
stack1.push(stack2.top());
stack2.pop();
}
return res;
}
private:
stack<int> stack1; // in
stack<int> stack2; // out
};用两个栈实现队列,队列是FIFO,栈是FILO。
1、栈和队列差别在弹出元素时,所以第二个栈的作用是弹出时中转,定义两个栈名为in和out
2、入队--向in栈压栈
3、出队--out栈清空->in栈倒入out栈->out栈顶弹出->out栈捣毁in栈
欢迎交流指正!!!

查看26道真题和解析