1. 程式人生 > 其它 >01 用棧實現佇列(leecode 232)

01 用棧實現佇列(leecode 232)

技術標籤:# 資料結構與演算法05-棧與佇列資料結構

1 問題

請你僅使用兩個棧實現先入先出佇列。佇列應當支援一般佇列的支援的所有操作(push、pop、peek、empty):

實現 MyQueue 類:

void push(int x) 將元素 x 推到佇列的末尾
int pop() 從佇列的開頭移除並返回元素
int peek() 返回佇列開頭的元素
boolean empty() 如果佇列為空,返回 true ;否則,返回 false

說明:

你只能使用標準的棧操作 —— 也就是隻有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的語言也許不支援棧。你可以使用 list 或者 deque(雙端佇列)來模擬一個棧,只要是標準的棧操作即可。

進階:

你能否實現每個操作均攤時間複雜度為 O(1) 的佇列?換句話說,執行 n 個操作的總時間複雜度為 O(n) ,即使其中一個操作可能花費較長時間。

示例:

輸入:
[“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 1, 1, false]

解釋:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)

myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

提示:

1 <= x <= 9
最多呼叫 100 次 push、pop、peek 和 empty
假設所有操作都是有效的 (例如,一個空的佇列不會呼叫 pop 或者 peek 操作)

2 解法

使用棧來模式佇列的行為,如果僅僅用一個棧,是一定不行的,所以需要兩個棧「一個輸入棧,一個輸出棧」,這裡要注意輸入棧和輸出棧的關係。

在push資料的時候,只要資料放進輸入棧就好,「但在pop的時候,操作就複雜一些,輸出棧如果為空,就把進棧資料全部匯入進來(注意是全部匯入)」,再從出棧彈出資料,如果輸出棧不為空,則直接從出棧彈出資料就可以了。

最後如何判斷佇列為空呢?「如果進棧和出棧都為空的話,說明模擬的佇列為空了。」

在程式碼實現的時候,會發現pop() 和 peek()兩個函式功能類似,程式碼實現上也是類似的,可以思考一下如何把程式碼抽象一下。

class MyQueue {
public:
    //定義入棧與出棧
    stack<int> stackIn;
    stack<int> stackOut;
    /** Initialize your data structure here. */
    MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        //入棧中壓入元素
        stackIn.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        //當出棧為空時,從入棧中取出全部元素放進出棧
        if(stackOut.empty())
        {
            //取出入棧的所有元素
            while(!stackIn.empty())
            {
                //將入棧中元素放入出棧
                stackOut.push(stackIn.top());
                //彈出入棧中元素
                stackIn.pop();
            }
        }
        //出棧不為空時,直接出棧
        int res = stackOut.top();
        stackOut.pop();
        return res;
    }
    
    /** 獲取佇列開頭元素 **/
    int peek() {
        //利用pop()方法獲取開頭元素
        int top = this->pop();
        //因為pop函式彈出了元素,將pop彈出的元素放回佇列開頭
        stackOut.push(top);
        return top;
    }


    /** Returns whether the queue is empty. */
    bool empty() {
        //入棧與出棧都為空時,則佇列為空
        return stackIn.empty() && stackOut.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();
 */