剑指Offer——用两个栈实现队列

Question

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

Solution

  • stack1用来push新到来的数据

  • stack2用来pop数据,如果stack2为空,那么就将stack1的数据移动到stack2,这样最先push到stack1的最后push到stack2.

  • 例如 push(1),push(2),push(3),stack1栈中顺序为321,如果再次push到stack2中的话,stack2中的顺序为123,刚好1最先被pop出去,满足队列的特点。

Code

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

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

private:
    stack<int> stack1;
    stack<int> stack2;
};
posted @ 2017-06-30 23:02  清水汪汪  阅读(125)  评论(0编辑  收藏  举报