兩個棧實現一佇列:
阿新 • • 發佈:2018-12-06
兩個棧實現一佇列:
要加入輔助棧,進行反轉操作
棧的順序為後進先出,而佇列的順序為先進先出。使用兩個棧實現佇列,一個元素需要經過兩個棧才能出佇列,在經過第一個棧時元素順序被反轉,經過第二個棧時再次被反轉,此時就是先進先出順序。
class MyQueue { Stack<Integer> in=new Stack<>(); Stack<Integer> out=new Stack<>(); /** Initialize your data structure here. */ public MyQueue() { } /** Push element x to the back of queue. */ //先入棧 public void push(int x) { in.push(x); } /** Removes the element from in front of queue and returns that element. */ //要遵循佇列的先入先出,應該讓元素從入棧中先進入輔助棧,再出棧 public int pop() { inToOut(); return out.pop(); } //執行出棧入棧操作 public void inToOut() { if(out.isEmpty()){ while(!in.isEmpty()){ out.push(in.pop()); } } } /** Get the front element. */ public int peek() { inToOut(); return out.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return in.isEmpty()&&out.isEmpty(); } } /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */