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

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

解法:
机制总结起来很简单:
入队 → 压入栈1
出队 → 栈2不空时,弹出栈2的栈顶元素,如果栈2空则将栈1元素逐个弹出压入栈2

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

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

private:
    stack<int> stack1;
    stack<int> stack2;
};
发布了55 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_38204302/article/details/104278260