剑指offer-用两个栈实现队列

来源:互联网 发布:仿淘宝购物车代码 编辑:程序博客网 时间:2024/04/30 05:59

问题

题目:[用两个栈实现队列]

思路

入队好办,出队的时候把一个栈的元素倒入另外一个栈即可。

代码

class Solution{public:    void push(int node) {        stack1.push(node);           }    int pop() {        helper(stack1,stack2);        int front = stack2.top();        stack2.pop();        helper(stack2, stack1);        return front;    }private:    void helper( stack<int>& s1, stack<int>& s2 ){        while(!s1.empty()){            int top = s1.top();            s1.pop();            s2.push(top);        }    }private:    stack<int> stack1;    stack<int> stack2;};
0 0
原创粉丝点击