Implement Stack using Queues解題報告

Description:

Implement the following operations of a stack using queues.

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

Link:

https://leetcode.com/problems/implement-stack-using-queues/#/description

解題方法:

queue::back()可以解決top()函數(shù)
每次pop()時都把隊伍頭部的元素push()進尾部,做size-1次,剩下的第一個元素就是之前隊伍尾部的元素。

Time Complexity:

pop() : O(N)
其余:O(1)

完整代碼:

class MyStack 
{
private: 
    queue<int> q1;
public:
    /** Push element x onto stack. */
    void push(int x) 
    {
        q1.push(x);
    }
    /** Removes the element on top of the stack and returns that element. */
    int pop() 
    {
        int len = q1.size() - 1;
        while(len--)
        {
            q1.push(q1.front());
            q1.pop();
        }
        int temp = q1.front();
        q1.pop();
        return temp;
    }
    /** Get the top element. */
    int top() 
    {
        return q1.back();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() 
    {
        return q1.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,890評論 0 33
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,641評論 5 6
  • 叮鈴鈴,叮鈴鈴……一陣急促的鬧鈴聲將我從美夢中吵醒,媽媽推開房門進來指了指鬧鐘對我說:“還不起來,第一天軍訓(xùn)就想遲...
    聽風(fēng)入耳閱讀 257評論 0 0
  • 今天,我為自己大學(xué)四年的文字作序,不是為了將自己四年的生活炫耀給旁人觀賞,因為一旦踏出大學(xué)的校門,這些經(jīng)歷...
    Glomi閱讀 379評論 2 2
  • 我初入華園,初識華園,初明大學(xué),初步大學(xué),都因為我大學(xué)的第一堂大課----軍訓(xùn)??赡芩俏胰松械淖詈笠淮诬娪?xùn),而...
    魚的靜時光閱讀 584評論 0 19

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