题目

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

思路

本题不难,首先了解队列的Push操作和Pop操作。在stack和queue中,Push位在队尾插入数据,Pop为弹出队尾或队首数据但不返回值,但本题中Pop操作要返回数据。然后是stack,stack主要用到了empty,pop,top,push四个操作。我的想法是这样的,用stack1实现push 操作,stack2实现pop操作。push 时先将数据时将stack2中数据移入stack1,然后队尾插入,pop时先将数据从stack1数据移入stack2中,然后top操作返回stack2队尾的值,同时执行pop操作移除该值。

代码

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

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

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