Implement Queue using Stacks解題報告

Description:

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.

Link:

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

解題方法:

用兩個棧in和out來解決,當(dāng)調(diào)用函數(shù)pop()peek()時,當(dāng)out為空時,把in棧的元素壓到out里面去,然后對out進(jìn)行pop()top()的調(diào)用。

Time Complexity:

pop()peek():O(1)到 O(N)

完整代碼:

class MyQueue 
{
private:
    stack<int> inS;
    stack<int> outS;
    void inToOut()
    {
        while(!inS.empty())
        {
            outS.push(inS.top());
            inS.pop();
        }
    }
public:
    /** Push element x to the back of queue. */
    void push(int x) 
    {
        inS.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() 
    {
        if(outS.empty())
            inToOut();
        int front = outS.top();
        outS.pop();
        return front;
    }
    
    /** Get the front element. */
    int peek() 
    {
        if(outS.empty())
            inToOut();
        return outS.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() 
    {
        return inS.empty() && outS.empty();
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,936評論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,260評論 0 23
  • 如果人生是一幅美麗的畫卷,軍訓(xùn)就是畫卷上最鮮艷的色彩;如果人生是大海,軍訓(xùn)就是大海中的燈塔。軍訓(xùn)就像一杯濃郁而久遠(yuǎn)...
    083閱讀 203評論 0 0
  • 啼 破天 見新歡 風(fēng)流少年 側(cè)帽為揚鞭 初遇亭亭展顏、 星光璀璨落眉間 雪月夜依偎不覺寒 風(fēng)兮云兮驟變似轉(zhuǎn)眼 流年...
    俠女小艾閱讀 385評論 0 0
  • 一個像獅子寶寶那么小的石頭 迷路了 它一定是在打僵尸的時候 轉(zhuǎn)了一圈 看不到媽媽 把僵尸給打倒了 才迷路的吧 一個...
    小雅鹿鳴閱讀 246評論 0 0

友情鏈接更多精彩內(nèi)容