【牛客网】用两个栈实现队列

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

一个栈压入再压入到另一个栈即是队列。这里要注意来回压。

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

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

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




猜你喜欢

转载自blog.csdn.net/u013721521/article/details/80595043