队列实现栈
/** Initialize your data structure here. */
private Queue<Integer> q;
private Integer tail;//记录栈顶元素
public MyStack() {
q = new LinkedList<>();
tail = 0;
}
/** Push element x onto stack. */
public void push(int x) {
q.add(x);
tail = x;//每添加一个元素 就将最后一个元素赋值给tail
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
for(int i=0;i<q.size()-2;i++){
q.add(q.remove());
}
tail = q.remove();//将倒数第二个元素存储到tail 用以弹出tail
q.add(tail);
return q.remove();
}
/** Get the top element. */
public int top() {
return tail;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}