Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Implement the MyStack class:
Input ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 2, 2, false] Explanation MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False
Constraints:
这道题的思路是准备两个queue和一个integer来记录top,每次加入的时候,就加入到应用queue里,并且更新top的值。这个过程是O(1)。pop的时候,把应用queue里除了最后一个值都加入到准备queue里。同时top也要随着这个过程不停更新。最后top就停留在之前应用queue的倒数第二个值。这时候把应用queue的最后一个值弹出,这就是最后要返回的值。但是在返回之前,把应用queue和准备queue的名字互换。这个过程是O(n)。top就直接返回top,empty就返回是否size为0. 这两个过程都是O(1)
注意:
class MyStack { Queue<Integer> useq; Queue<Integer> waitq; int top; public MyStack() { useq = new LinkedList<Integer>(); waitq = new LinkedList<Integer>(); top = Integer.MIN_VALUE; } public void push(int x) { this.useq.offer(x); this.top = x; } public int pop() { if (!empty()){ int n = useq.size(); for (int i = 0; i < n - 1; i++) { this.top = useq.poll(); this.waitq.offer(top); } int rst = useq.poll(); Queue<Integer> tmp = this.useq; this.useq = this.waitq; this.waitq = tmp; return rst; } else { return Integer.MIN_VALUE; } } public int top() { return top; } public boolean empty() { return useq.size() == 0; } } /** * 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(); */