使用隊列實現棧的下列操作:
push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否為空
注意:
你只能使用隊列的基本操作-- 也就是?push to back, peek/pop from front, size, 和?is empty?這些操作是合法的。
你所使用的語言也許不支持隊列。?你可以使用 list 或者 deque(雙端隊列)來模擬一個隊列?, 只要是標準的隊列操作即可。
你可以假設所有操作都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操作)。
思路:
棧和隊列互相模擬
class MyStack {private Queue<Integer> a;//輸入隊列private Queue<Integer> b;//輸出隊列public MyStack() {a = new LinkedList<>();b = new LinkedList<>();}public void push(int x) {a.offer(x);// 將b隊列中元素全部轉給a隊列while(!b.isEmpty())a.offer(b.poll());// 交換a和b,使得a隊列沒有在push()的時候始終為空隊列Queue temp = a;a = b;b = temp;}public int pop() {return b.poll();}public int top() {return b.peek();}public boolean empty() {return b.isEmpty();}
}/*** Your MyStack object will be instantiated and called as such:* MyStack obj = new MyStack();* obj.push(x);* int param_2 = obj.pop();* int param_3 = obj.top();* boolean param_4 = obj.empty();*/
?