【leetcode】232. Implement Queue using Stacks

題目:
在這裏插入圖片描述


思路:
設置兩個棧。用這兩個棧倒騰一下數據就可以了。

代碼實現:

class MyQueue {
private:
    stack<int> stack[2];
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        stack[1].push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int t;
        if (!stack[0].empty()){
            t = stack[0].top();
            stack[0].pop();
        }else{
            while (!stack[1].empty()){
                stack[0].push(stack[1].top());
                stack[1].pop();
            }
            t = stack[0].top();
            stack[0].pop();
        }
        return t;
    }
    
    /** Get the front element. */
    int peek() {
        int t;
        if (!stack[0].empty()){
            t = stack[0].top();
        }else{
            while (!stack[1].empty()){
                stack[0].push(stack[1].top());
                stack[1].pop();
            }
            t = stack[0].top();
        }
        return t;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
       return stack[0].empty() && stack[1].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();
 */

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章