國際慣例,先上題目:
Implement the following Operations of a queue using stacks.
Notes:
push to top,peek/pop from top,size, andis emptyoperations are valid.
這道題個人覺得屬于比較有意思的一道題><還有一道類似的用queue來完成stack的,不過我還沒有做到,暫且不說。
這道題比較好想到的方法是雙stack法,因為剛好stack和queue的順序是相反的。
試想建立兩個stack,當把所有數據從stack a中轉移到b的時候,其數據排列就會發生變化,這樣一來就很好理解了。
不過也可以只建立一個stack,這里就需要swap來輔助,這個會比較節省時間一點。
不過我暫時只寫了雙stack的用法,下次有機會寫下單stack的哈哈。
個人覺得這道題難點就在第一個method上,后面都很簡單,直接套用stack的method即可。
class MyQueue { Stack<Integer> a=new Stack<Integer>(); Stack<Integer> b=new Stack<Integer>(); // Push element x to the back of queue. public void push(int x) { //specail case if(a.isEmpty()){ a.push(x); }else{ while(!a.isEmpty()){ b.push(a.pop()); } a.push(x); while(!b.isEmpty()){ a.push(b.pop()); } } } // Removes the element from in front of queue. public void pop() { a.pop(); } // Get the front element. public int peek() { return a.peek(); } // Return whether the queue is empty. public boolean empty() { return a.isEmpty(); }}新聞熱點
疑難解答