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:
void push(int x) Pushes element x to the top of the stack.
int pop() Removes the element on the top of the stack and returns it.
int top() Returns the element on the top of the stack.
boolean empty() Returns true if the stack is empty, false otherwise.
Notes:
You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue’s standard operations.
Example 1:
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
用两个队列实现一个栈。
只能用队列的现有操作(先入先出)。
思路:
队列的现有操作是先入先出,而栈是后入先出,
栈的pop操作时,要取queue最后进的数字,而queue本身的pop操作则是取出最先压进的数字,
要取最后一个数字则需要把前面所有的数字都取出来,才能取出最后的。
然后再把前面取出的所有数字存回去。
而这里用另外一个queue保存取出的所有数字(除了最后一个),然后不必再存回去,只需要交换两个队列即可。
top操作是返回栈顶的数字,但不删除,
所以存入数字时要记录最后存入的数字,
pop时要记录倒数第2个取出的数字(因为最后一个已删除)。
Java实现上要注意Queue是接口,不能instance化,使用时用
这里使用ArrayDeque,也可用LinkedList。
class MyStack {
Queue<Integer> q1, q2;
int top = 0;
public MyStack() {
q1 = new ArrayDeque<Integer>();
q2 = new ArrayDeque<Integer>();
}
public void push(int x) {
q1.offer(x);
top = x;
}
public int pop() {
while(q1.size() > 1) {
top = q1.poll();
q2.offer(top);
}
int res = q1.poll();
Queue<Integer> tmp = q1;
q1 = q2;
q2 = tmp;
return res;
}
public int top() {
return top;
}
public boolean empty() {
return (q1.size() == 0);
}
}