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

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

[LeetCode] Implement Stack using Queues

2019-11-15 01:05:54
字體:
供稿:網(wǎng)友
[LeetCode] Implement Stack using Queues

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 useonlystandard operations of a queue -- which means onlypush to back,peek/pop from front,size, andis emptyoperations 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).

這道題就不說了,和之前說過的那道implement Queue using Stack的思路差不多。

還是建立兩個Queue之間互相轉(zhuǎn)換就好,記得所寫的算法運行后必須保證兩個queue的其中一個隊列為空。

我的答案這里把push寫成了offer然后pop寫成了poll,不過leetcode還是識別了哈哈。

因為我寫的時候有參考java platform standard(http://docs.Oracle.com/javase/7/docs/api/java/util/Queue.html#peek())這里面還是寫的offer/poll所以就……。

class MyStack {    LinkedList<Integer> a=new LinkedList<Integer>();    LinkedList<Integer> b=new LinkedList<Integer>();    // Push element x onto stack.    public void push(int x) {        if(a.size()==0){            a.offer(x);        }else{           if(a.size()>0){               b.offer(x);               int size=a.size();               while(size>0){                   b.offer(a.poll());                   size--;               }           }else if(b.size()>0){               a.offer(x);               int size=b.size();               while(size>0){                   a.offer(b.poll());                   size--;               }           }                    }    }    // Removes the element on top of the stack.     public void pop() {         if(a.size()>0){            a.poll();         }else if(b.size()>0){             b.poll();         }            }    // Get the top element.i    public int top() {        if(a.size()>0){            return a.peek();        }else if(b.size()>0){            return b.peek();        }        return 0;    }    // Return whether the stack is empty.    public boolean empty() {        return a.isEmpty()&b.isEmpty();    }}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 霍林郭勒市| 西乡县| 浦江县| 阜平县| 金平| 甘谷县| 高州市| 龙口市| 梓潼县| 海盐县| 禄丰县| 东海县| 铜鼓县| 德化县| 阿克苏市| 抚宁县| 仪陇县| 来宾市| 如东县| 宁南县| 南京市| 昌都县| 金堂县| 绍兴市| 神农架林区| 涞水县| 舟山市| 商河县| 琼海市| 旬邑县| 察雅县| 施秉县| 来宾市| 分宜县| 双城市| 丹江口市| 子长县| 大名县| 呼和浩特市| 胶南市| 贞丰县|