232. 用栈实现队列

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

/**
 * 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();
 */

将一个栈当作输入栈,用于压入 \texttt{push}push 传入的数据;另一个栈当作输出栈,用于 \texttt{pop}pop 和 \texttt{peek}peek 操作。

每次 \texttt{pop}pop 或 \texttt{peek}peek 时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序。

 

posted on 2021-03-05 09:46  hannah_id  阅读(68)  评论(0)    收藏  举报

导航