星空网 > 软件开发 > Java

[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 use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, 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).

     

     这道题就不说了,和之前说过的那道implement Queue using Stack的思路差不多。

     还是建立两个Queue之间互相转换就好,记得所写的算法运行后必须保证两个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();  }}

 

 

     




原标题:[LeetCode] Implement Stack using Queues

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

德国VAT申报指南完整流程一步步走:https://www.kjdsnews.com/a/1387918.html
德国VAT申报指南一步一步进入申报入口:https://www.kjdsnews.com/a/1387919.html
德国VAT申报指南一步一步走向成功:https://www.kjdsnews.com/a/1387920.html
德国VAT申报失误,可以重新申报吗?:https://www.kjdsnews.com/a/1387921.html
德国VAT申报失误可否重新申报?:https://www.kjdsnews.com/a/1387922.html
德国VAT申报流程详解:https://www.kjdsnews.com/a/1387923.html
宜宾江安-宜宾江安县旅游景点大全:https://www.vstour.cn/a/404232.html
浏阳市里面哪里好玩的地方 浏阳市内有什么好玩的地方:https://www.vstour.cn/a/404233.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流