Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.
思路:想要将队列实现栈的功能,即先进先出 与 后进先出的转换
需要额外的数组来记录当前的状态,也就是队列中最后进入的元素是谁,怎么抛出他
import java.util.concurrent.*;
class MyStack {
// Push element x onto stack.
ArrayBlockingQueue<Integer> queue=new ArrayBlockingQueue<Integer>(8);
List<Integer> list=new ArrayList<>();
public void push(int x) {
queue.add(x);
list.add(x);
}
// Removes the element on top of the stack.
public void pop() {
queue.remove(list.get(list.size()-1));
list.remove(list.size()-1);
}
// Get the top element.
public int top() {
return list.get(list.size()-1);
}
// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}