Implement Stack using Queues
用queue写一个stack. 这里有很多的不同实现方法, 最简单的就是当push的时候, 改成stack.
class MyStack {
// Push element x onto stack.
Queue<Integer> q = new LinkedList<Integer>();
public void push(int x) {
q.offer(x);
for(int i = 0 ; i < q.size()-1; i++){
q.offer(q.peek());
q.poll();
}
}
// Removes the element on top of the stack.
public void pop() {
q.poll();
}
// Get the top element.
public int top() {
return q.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return q.isEmpty();
}
}