剑指Offer面试题9 两个栈实现队列

题目描述

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

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

    int pop() {
        int tag;
        if(stack2.empty())//如果 2栈为空,将 1栈中的元素放入第二个栈,
        {
              while(stack1.size()!=0){
                stack2.push( stack1.top());
                stack1.pop();
            }
        }
        tag = stack2.top();//第二个栈首元素出栈
        stack2.pop();
        return tag;
    }

private:
    stack stack1;
    stack stack2;
};

你可能感兴趣的:(剑指Offer面试题9 两个栈实现队列)