国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 广饶县| 廊坊市| 万全县| 论坛| 普陀区| 福海县| 淄博市| 兴安盟| 长岛县| 乌海市| 册亨县| 夏津县| 韶山市| 北川| 密云县| 河北省| 韩城市| 太康县| 乐安县| 芮城县| 北宁市| 新丰县| 广德县| 读书| 五家渠市| 江安县| 阳高县| 芦山县| 长阳| 迁西县| 盘锦市| 建平县| 柳林县| 昌黎县| 丹棱县| 玉林市| 体育| 公安县| 巴楚县| 怀安县| 广昌县|