用两个栈实现队列

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

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

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

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

栈与队列的不同在出去的时候的顺序不同

用栈实现先进先出,需要在出栈的时候,全部出栈A存到另外一个栈B,然后再从另外一个栈B出来,这样就可以由两次先进后出实现先进先出。

注意出栈的时候要判断栈B是否为空,若空则栈A全部存入栈B,同时栈A也空了,这样才不会出现一个数值同时存在两个栈中

原文地址:https://www.cnblogs.com/qin5429/p/12693352.html