用两个栈实现队列

题目描述

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

代码

class Solution
{
public:
    void push(int node) {
        while (!stack1.empty()) {
            int tmp = stack1.top();
            stack2.push(tmp);
            stack1.pop();
        }
        stack1.push(node);
         while (!stack2.empty()) {
            int tmp = stack2.top();
            stack1.push(tmp);
            stack2.pop();
        }
    }

    int pop() {
        int result = stack1.top();
        stack1.pop();
        return result;
        
    }

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

posted on 2017-03-11 18:49  jec  阅读(96)  评论(0编辑  收藏  举报

导航