用两个栈实现队列

你快乐吗?

Posted by bbkgl on September 26, 2019

用两个栈实现队列


思路很简单:

  • 入栈只入栈1
  • 出栈只从栈2出,出栈时如果栈2右元素则顶部元素出栈,否则让栈1元素全部压入到栈2,然后栈2最上面元素出栈

代码如下:

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

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

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