[225&232]用隊列實現(xiàn)棧&用棧實現(xiàn)隊列

題目描述

  • [225]僅使用兩個棧實現(xiàn)先入先出隊列泵三。隊列應當支持一般隊列支持的所有操作(push、pop衔掸、peek烫幕、empty)
  • [232]僅使用兩個隊列實現(xiàn)一個后入先出(LIFO)的棧,并支持普通棧的全部四種操作(push敞映、top纬霞、pop 和 empty)

一、個人拙見

對比隊列與棧的特性區(qū)別驱显,一個是先進先出,一個是先進后出,然后埃疫,嗯~ o( ̄▽ ̄)o伏恐!
用棧實現(xiàn)隊列

class MyQueue {
    Stack<Integer> s1;
    Stack<Integer> s2;

    public MyQueue() {
        s1 = new Stack<Integer>();
        s2 = new Stack<Integer>();
    }

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

    /**
     * Removes the element from in front of queue and returns that element.
     */
    public int pop() {
        peek();
        return s2.pop();
    }

    /**
     * Get the front element.
     */
    public int peek() {
        if (s2.isEmpty()) {
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        if (s2.isEmpty()) {
            return -1;
        } else {
            return s2.peek();
        }
    }

    /**
     * Returns whether the queue is empty.
     */
    public boolean empty() {
        return s1.isEmpty() && s2.isEmpty();
    }
}

用隊列實現(xiàn)棧

class MyStack {
    Queue<Integer> q1, q2;

    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
    }

    /**
     * Push element x onto stack.
     */
    public void push(int x) {
        q1.add(x);
    }

    /**
     * Removes the element on top of the stack and returns that element.
     */
    public int pop() {
        top();
        return q1.remove();
    }

    /**
     * Get the top element.
     */
    public int top() {
        if (q1.isEmpty()) {
            while (!q2.isEmpty()) {
                q1.add(q2.remove());
            }
        }
        if (q1.isEmpty()) return -1;
        while (q1.size() > 1) {
            q2.add(q1.remove());
        }
        return q1.peek();
    }

    /**
     * Returns whether the stack is empty.
     */
    public boolean empty() {
        return q1.isEmpty() && q2.isEmpty();
    }
}

二、labuladong解答

作者:labuladong
這位大牛的方法栓霜,只用了一個隊列實現(xiàn)翠桦。確實,腦袋被前一道題限制了胳蛮,以為還是要用倆隊列销凑。。仅炊。
且用了個變量斗幼,存儲top

class MyStack {
    Queue<Integer> q = new LinkedList<>();
    int topElem = 0;

    public void push(int x) {
        // x 是隊列的隊尾,是棧的棧頂
        q.offer(x);
        topElem = x;
    }

    public int top() {
        return topElem;
    }

    public int pop() {
        int size = q.size();
        // 留下隊尾 2 個元素
        while (size > 2) {
            q.offer(q.poll());
            --size;
        }
        // 記錄新的隊尾元素
        // 此時的位置即為刪除最后元素后的新的最后元素
        topElem = q.peek();
        q.offer(q.poll());
        // 刪除之前的隊尾元素
        return q.poll();
    }

    public boolean empty() {
        return q.isEmpty();
    }
}

三抚垄、官方解答

作者:LeetCode-Solution

解法一蜕窿、兩個隊列

思路

為了滿足棧的特性,即最后入棧的元素最先出棧呆馁,在使用隊列實現(xiàn)棧時桐经,應滿足隊列前端的元素是最后入棧的元素≌懵耍可以使用兩個隊列實現(xiàn)棧的操作阴挣,其中 queue 1 用于存儲棧內的元素,queue 2 作為入棧操作的輔助隊列纺腊。
入棧操作時畔咧,首先將元素入隊到 queue 2 ,然后將 queue 1 的全部元素依次出隊并入隊到 queue 2 摹菠,此時 queue 2 的前端的元素即為新入棧的元素盒卸,再將 queue 1 和 queue 2 互換,則 queue 1 的元素即為棧內的元素次氨,queue 1 的前端和后端分別對應棧頂和棧底蔽介。

代碼

class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;

    /** Initialize your data structure here. */
    public MyStack() {
        queue1 = new LinkedList<Integer>();
        queue2 = new LinkedList<Integer>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue2.offer(x);
        while (!queue1.isEmpty()) {
            queue2.offer(queue1.poll());
        }
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue1.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return queue1.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue1.isEmpty();
    }
}

復雜度分析

  • 時間復雜度:入棧操作 O(n),其余操作都是 O(1)煮寡。
  • 空間復雜度:O(n)虹蓄,其中 n 是棧內的元素。需要使用兩個隊列存儲棧內的元素幸撕。

解法二薇组、一個隊列

思路

使用一個隊列時,為了滿足棧的特性坐儿,即最后入棧的元素最先出棧律胀,同樣需要滿足隊列前端的元素是最后入棧的元素宋光。
入棧操作時,首先獲得入棧前的元素個數(shù) n炭菌,然后將元素入隊到隊列罪佳,再將隊列中的前 n 個元素(即除了新入棧的元素之外的全部元素)依次出隊并入隊到隊列,此時隊列的前端的元素即為新入棧的元素黑低,且隊列的前端和后端分別對應棧頂和棧底赘艳。

代碼

class MyStack {
    Queue<Integer> queue;

    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<Integer>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        int n = queue.size();
        queue.offer(x);
        for (int i = 0; i < n; i++) {
            queue.offer(queue.poll());
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}

復雜度分析

  • 時間復雜度:入棧操作 O(n),其余操作都是 O(1)克握。
  • 空間復雜度:O(n)蕾管,其中 n 是棧內的元素。需要使用一個隊列存儲棧內的元素菩暗。
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末掰曾,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子勋眯,更是在濱河造成了極大的恐慌婴梧,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,907評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件客蹋,死亡現(xiàn)場離奇詭異塞蹭,居然都是意外死亡,警方通過查閱死者的電腦和手機讶坯,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評論 3 395
  • 文/潘曉璐 我一進店門番电,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人辆琅,你說我怎么就攤上這事漱办。” “怎么了婉烟?”我有些...
    開封第一講書人閱讀 164,298評論 0 354
  • 文/不壞的土叔 我叫張陵娩井,是天一觀的道長。 經(jīng)常有香客問我似袁,道長洞辣,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,586評論 1 293
  • 正文 為了忘掉前任昙衅,我火速辦了婚禮扬霜,結果婚禮上,老公的妹妹穿的比我還像新娘而涉。我一直安慰自己著瓶,他們只是感情好,可當我...
    茶點故事閱讀 67,633評論 6 392
  • 文/花漫 我一把揭開白布啼县。 她就那樣靜靜地躺著材原,像睡著了一般沸久。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上华糖,一...
    開封第一講書人閱讀 51,488評論 1 302
  • 那天麦向,我揣著相機與錄音,去河邊找鬼客叉。 笑死,一個胖子當著我的面吹牛话告,可吹牛的內容都是我干的兼搏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,275評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼沙郭,長吁一口氣:“原來是場噩夢啊……” “哼佛呻!你這毒婦竟也來了?” 一聲冷哼從身側響起病线,我...
    開封第一講書人閱讀 39,176評論 0 276
  • 序言:老撾萬榮一對情侶失蹤吓著,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后送挑,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體绑莺,經(jīng)...
    沈念sama閱讀 45,619評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,819評論 3 336
  • 正文 我和宋清朗相戀三年惕耕,在試婚紗的時候發(fā)現(xiàn)自己被綠了纺裁。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,932評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡司澎,死狀恐怖欺缘,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情挤安,我是刑警寧澤谚殊,帶...
    沈念sama閱讀 35,655評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站蛤铜,受9級特大地震影響嫩絮,放射性物質發(fā)生泄漏。R本人自食惡果不足惜昂羡,卻給世界環(huán)境...
    茶點故事閱讀 41,265評論 3 329
  • 文/蒙蒙 一絮记、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧虐先,春花似錦怨愤、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽篮愉。三九已至,卻和暖如春差导,著一層夾襖步出監(jiān)牢的瞬間试躏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評論 1 269
  • 我被黑心中介騙來泰國打工设褐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留颠蕴,地道東北人。 一個月前我還...
    沈念sama閱讀 48,095評論 3 370
  • 正文 我出身青樓助析,卻偏偏與公主長得像犀被,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子外冀,可洞房花燭夜當晚...
    茶點故事閱讀 44,884評論 2 354

推薦閱讀更多精彩內容