LeetCode #232 Implement Queue using Stacks 用棧實(shí)現(xiàn)隊(duì)列

232 Implement Queue using Stacks 用棧實(shí)現(xiàn)隊(duì)列

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.

Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false

Notes:

You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

題目描述:
使用棧實(shí)現(xiàn)隊(duì)列的下列操作:

push(x) -- 將一個(gè)元素放入隊(duì)列的尾部咖城。
pop() -- 從隊(duì)列首部移除元素残腌。
peek() -- 返回隊(duì)列首部的元素。
empty() -- 返回隊(duì)列是否為空积担。

示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false

說(shuō)明:

你只能使用標(biāo)準(zhǔn)的棧操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的悠瞬。
你所使用的語(yǔ)言也許不支持棧陕凹。你可以使用 list 或者 deque(雙端隊(duì)列)來(lái)模擬一個(gè)棧萝映,只要是標(biāo)準(zhǔn)的棧操作即可望忆。
假設(shè)所有操作都是有效的 (例如罩阵,一個(gè)空的隊(duì)列不會(huì)調(diào)用 pop 或者 peek 操作)。

思路:

參考LeetCode #225 Implement Stack using Queues 用隊(duì)列實(shí)現(xiàn)棧
使用 2個(gè)棧完成隊(duì)列

  • push()時(shí)間復(fù)雜度O(1), 空間復(fù)雜度O(1)
  • pop()時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(n)
  • top()時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(n)
  • empty()時(shí)間復(fù)雜度O(1), 空間復(fù)雜度O(1)

代碼:
C++:

class MyQueue 
{
public:
    /** Initialize your data structure here. */
    MyQueue() 
    {

    }

    /** Push element x to the back of queue. */
    void push(int x) 
    {
        in_stack.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() 
    {
        move(in_stack, out_stack);
        int result = out_stack.top();
        out_stack.pop();
        move(out_stack, in_stack);
        return result;
    }

    /** Get the front element. */
    int peek() 
    {
        move(in_stack, out_stack);
        int result = out_stack.top();
        move(out_stack, in_stack);
        return result;
    }

    /** Returns whether the queue is empty. */
    bool empty() 
    {
        return in_stack.empty();
    }
private:
    stack<int> in_stack;
    stack<int> out_stack;
    void move(stack<int> &a, stack<int> &b) 
    {
        while (!a.empty()) 
        {
            b.push(a.top());
            a.pop();
        }
    }
};

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

Java:

class MyQueue {

    private Stack<Integer> stack;
    private Stack<Integer> temp;
    private void move(Stack<Integer> a, Stack<Integer> b) {
        while (!a.empty()) b.push(a.pop());
    }
    /** Initialize your data structure here. */
    public MyQueue() {
        stack = new Stack<>();
        temp = new Stack<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        stack.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        move(stack, temp);
        int result = temp.pop();
        move(temp, stack);
        return result;
    }

    /** Get the front element. */
    public int peek() {
        move(stack, temp);
        int result = temp.peek();
        move(temp, stack);
        return result;
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack.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();
 * boolean param_4 = obj.empty();
 */

Python:

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack = []

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.stack.append(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        temp = []
        while self.stack:
            temp.append(self.stack.pop())
        result = temp.pop()
        while temp:
            self.stack.append(temp.pop())
        return result

    def peek(self) -> int:
        """
        Get the front element.
        """
        temp = []
        while self.stack:
            temp.append(self.stack.pop())
        result = temp[-1]
        while temp:
            self.stack.append(temp.pop())
        return result

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return len(self.stack) == 0


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末启摄,一起剝皮案震驚了整個(gè)濱河市永脓,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌鞋仍,老刑警劉巖常摧,帶你破解...
    沈念sama閱讀 218,525評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異威创,居然都是意外死亡落午,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門肚豺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)溃斋,“玉大人,你說(shuō)我怎么就攤上這事吸申」=伲” “怎么了享甸?”我有些...
    開封第一講書人閱讀 164,862評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)梳侨。 經(jīng)常有香客問(wèn)我蛉威,道長(zhǎng),這世上最難降的妖魔是什么走哺? 我笑而不...
    開封第一講書人閱讀 58,728評(píng)論 1 294
  • 正文 為了忘掉前任蚯嫌,我火速辦了婚禮,結(jié)果婚禮上丙躏,老公的妹妹穿的比我還像新娘择示。我一直安慰自己,他們只是感情好晒旅,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評(píng)論 6 392
  • 文/花漫 我一把揭開白布栅盲。 她就那樣靜靜地躺著,像睡著了一般废恋。 火紅的嫁衣襯著肌膚如雪剪菱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,590評(píng)論 1 305
  • 那天拴签,我揣著相機(jī)與錄音孝常,去河邊找鬼。 笑死蚓哩,一個(gè)胖子當(dāng)著我的面吹牛构灸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播岸梨,決...
    沈念sama閱讀 40,330評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼喜颁,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了曹阔?” 一聲冷哼從身側(cè)響起半开,我...
    開封第一講書人閱讀 39,244評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎赃份,沒(méi)想到半個(gè)月后寂拆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,693評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡抓韩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評(píng)論 3 336
  • 正文 我和宋清朗相戀三年纠永,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片谒拴。...
    茶點(diǎn)故事閱讀 40,001評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡尝江,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出英上,到底是詐尸還是另有隱情炭序,我是刑警寧澤啤覆,帶...
    沈念sama閱讀 35,723評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站惭聂,受9級(jí)特大地震影響窗声,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜彼妻,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評(píng)論 3 330
  • 文/蒙蒙 一嫌佑、第九天 我趴在偏房一處隱蔽的房頂上張望豆茫。 院中可真熱鬧侨歉,春花似錦、人聲如沸揩魂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)火脉。三九已至牵舵,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間倦挂,已是汗流浹背畸颅。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留方援,地道東北人没炒。 一個(gè)月前我還...
    沈念sama閱讀 48,191評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像犯戏,于是被迫代替她去往敵國(guó)和親送火。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評(píng)論 2 355