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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/86902440
  • 描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
  • 分析:用两个栈来实现队列,一个栈用来存储Push的值,用另一个栈来进行Pop操作。
  • 思路一:
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if (stack2.empty()) {
            int n = stack1.size();
            for (int i = 0 ;i < n; i++) {
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        int top = stack2.top();
        stack2.pop();
        return top;
    }

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

猜你喜欢

转载自blog.csdn.net/m0_38088298/article/details/86902440