Implement the following operations of a stack using queues.
Notes:
push to back
, peek/pop from front
, size
, and is empty
operations are valid.
这道题就不说了,和之前说过的那道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(); } }