用两个栈实现队列:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
见代码注释
例子:
假设操作为如下所展示
| 操作 | 队列 | 栈1 | 栈2 | 
|---|---|---|---|
| push 1 | 1 | 1 | null | 
| push 2 | 1,2 | 1,2 | null | 
| pop | 2 | 1,2 | 2,1→2 | 
| pop | null | 1,2 | 2→null | 
| push6 | 6 | 1,2,6 | null | 
| pop | null | 1,2,6 | 6,2,1→6,2 | 
class Solution
{
public:
    void push(int node) {
        stack1.push(node);//加入栈1
    }
    int pop() {
        if(stack2.empty()){//如果栈2时空的,将栈1的东西倒入栈2
            while(!stack1.empty()){
            
            stack2.push(stack1.top());
            stack1.pop();
            }
        }
            int nn = stack2.top();//出栈
        stack2.pop();
        return nn;
    }
private:
    stack<int> stack1;
    stack<int> stack2;
};