【剑指offer】用两个栈实现队列

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

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

    int pop() {
        int ans;
        //取出stack1栈底的元素:将Stack1中的元素全部出栈,暂时放在stack2中
        while (true) {
            ans = stack1.top();
            stack1.pop();
            if (stack1.empty()) {
                break;
            }
            stack2.push(ans);
        }
        //还原Stack1:将元素按入stack1的顺序再放回去,此时栈底元素已经取出
        while (!stack2.empty()) {
            stack1.push(stack2.top());
            stack2.pop();
        }
        return ans;
    }

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

 

posted @ 2018-12-27 00:15  Little_Shel  阅读(101)  评论(0编辑  收藏  举报