剑指offer面试题9. 用两个队列实现一个栈

欢迎访问我的剑指offer(第二版)题解目录
对应的Leetcode题目可点击leetcode 225. Implement Stack using Queues

题目描述

Implement the following operations of a stack using queues.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • empty() – Return whether the stack is empty.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

Notes:

  • You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

算法设计

为了避免元素的大量复制,我们可以定义一个长度为2的队列数组q,另外定义一个标志变量f指示目前q[f]负责模拟压栈操作,q[f xor 1]负责模拟弹栈操作。当执行压栈操作时,直接向q[f]中压入元素。当执行弹栈操作时,先检测q[f xor 1]元素个数是否大于1,如果正好等于1,那么弹出q[f xor 1]中的这个元素即可;如果大于1,逐个将q[f xor 1]中的元素弹出到q[f]中,直至q[f xor 1]元素个数等于1,然后将这个元素弹出即可。弹栈操作执行完成后,一定要注意要执行f^=1语句,因为之后负责模拟压栈、弹栈操作的队列要进行交换。

C++代码

class MyStack {
  public:
    /** Initialize your data structure here. */
    array<queue<int>, 2> q{};
    int f = 0;
    MyStack() {}

    /** Push element x onto stack. */
    void push(int x) { q[f].push(x); }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        while (q[f].size() > 1) {
            q[f xor 1].push(q[f].front());
            q[f].pop();
        }
        int x = q[f].front();
        q[f].pop();
        f ^= 1;
        return x;
    }

    /** Get the top element. */
    int top() {
        int x = q[f].front();
        while (not q[f].empty()) {
            x = q[f].front();
            q[f xor 1].push(x);
            q[f].pop();
        }
        f ^= 1;
        return x;
    }

    /** Returns whether the stack is empty. */
    bool empty() { return q[0].empty() and q[1].empty(); }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
发布了528 篇原创文章 · 获赞 1015 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/richenyunqi/article/details/103647985