232. Implement Queue using Stacks

1.問題

  • 用stack來設計queue

2.想法

  • 當push時, 將所有reverseStack中的元素推入forwardStack;

  • 當pop時, 將所有forwardStack中的元素推入reverseStack

  • empty要確定兩個stack都是empty

3.程式碼

class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        if (forwardStack.empty()) {
            while (!reverseStack.empty()) {
                forwardStack.push(reverseStack.top());
                reverseStack.pop();
            }
        }
        forwardStack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if (reverseStack.empty()) {
            while (!forwardStack.empty()) {
                reverseStack.push(forwardStack.top());
                forwardStack.pop();
            }
        }
        int top = reverseStack.top();
        reverseStack.pop();
        return top;
    }
    
    /** Get the front element. */
    int peek() {
        if (reverseStack.empty()) {
            while (!forwardStack.empty()) {
                reverseStack.push(forwardStack.top());
                forwardStack.pop();
            }
        }
        int top = reverseStack.top();
        return top;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return forwardStack.empty() && reverseStack.empty();
    }
private:
    stack<int> forwardStack;
    stack<int> reverseStack;
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */

4.Performance

Last updated