1. 程式人生 > >232 Implement Queue using Stacks 用棧來實現隊列

232 Implement Queue using Stacks 用棧來實現隊列

whether light 操作 move bool problem rem http rip

使用棧來實現隊列的如下操作:

push(x) -- 將一個元素放入隊列的尾部。
pop() -- 從隊列首部移除元素。
peek() -- 返回隊列首部的元素。
empty() -- 返回隊列是否為空。
註意:

你只能使用標準的棧操作-- 也就是只有push to top, peek/pop from top, size, 和 is empty 操作是可使用的。
你所使用的語言也許不支持棧。你可以使用 list 或者 deque (雙端隊列)來模擬一個棧,只要你僅使用棧的標準操作就可以。
假設所有操作都是有效的,比如 pop 或者 peek 操作不會作用於一個空隊列上。

詳見:https://leetcode.com/problems/implement-queue-using-stacks/description/

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

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

  

232 Implement Queue using Stacks 用棧來實現隊列