Implement the following Operations of a stack using queues.
Notes:
push to back,peek/pop from front,size, andis emptyoperations are valid.
這道題就不說了,和之前說過的那道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(); }}
新聞熱點
疑難解答