国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Implement Queue using Stacks

2019-11-15 01:05:45
字體:
來源:轉載
供稿:網友
[LeetCode] Implement Queue using Stacks

國際慣例,先上題目:

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.

Notes:

    • You must useonlystandard operations of a stack -- which means onlypush to top,peek/pop from top,size, andis emptyoperations 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).

這道題個人覺得屬于比較有意思的一道題><還有一道類似的用queue來完成stack的,不過我還沒有做到,暫且不說。

這道題比較好想到的方法是雙stack法,因為剛好stack和queue的順序是相反的。

試想建立兩個stack,當把所有數據從stack a中轉移到b的時候,其數據排列就會發生變化,這樣一來就很好理解了。

不過也可以只建立一個stack,這里就需要swap來輔助,這個會比較節省時間一點。

不過我暫時只寫了雙stack的用法,下次有機會寫下單stack的哈哈。

個人覺得這道題難點就在第一個method上,后面都很簡單,直接套用stack的method即可。

class MyQueue {        Stack<Integer> a=new Stack<Integer>();    Stack<Integer> b=new Stack<Integer>();        // Push element x to the back of queue.    public void push(int x) {        //specail case        if(a.isEmpty()){            a.push(x);        }else{            while(!a.isEmpty()){                b.push(a.pop());            }            a.push(x);            while(!b.isEmpty()){                a.push(b.pop());            }        }            }    // Removes the element from in front of queue.    public void pop() {        a.pop();    }    // Get the front element.    public int peek() {        return a.peek();    }    // Return whether the queue is empty.    public boolean empty() {        return a.isEmpty();    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 周口市| 安化县| 兴化市| 三都| 象山县| 邯郸市| 兰考县| 如东县| 莒南县| 中山市| 凤凰县| 洛隆县| 宁强县| 聂拉木县| 阿克陶县| 斗六市| 牟定县| 宜都市| 任丘市| 楚雄市| 井陉县| 洱源县| 怀仁县| 万载县| 小金县| 贺兰县| 朔州市| 鄱阳县| 绥棱县| 黑河市| 阳谷县| 三明市| 宁晋县| 富蕴县| 玉溪市| 名山县| 阳泉市| 芦溪县| 隆回县| 洪江市| 武强县|