题意:用一个队列实现栈
题解:
(1)弹栈:将队头开始的前size()-1个元素全部出队然后重新入队,使队尾元素循环到队头,然后弹出
(2)获取栈顶元素:先将队头开始的前size()-1个元素全部出队然后重新入队,使队尾元素循环到队头,此时队头元素即为栈顶元素;然后再重新循环size()+1次,复原元素顺序
Java代码
class MyStack {
Queue<Integer> q = new LinkedList<>();
public MyStack() {
}
public void push(int x) {
q.offer(x);
}
public int pop() {
move(q.size() - 1);
return q.poll();
}
public int top() {
move(q.size() - 1);
int ans = q.peek();
move(q.size() + 1);
return ans;
}
public boolean empty() {
return q.isEmpty();
}
public void move(int t) {
while(t -- > 0) {
q.offer(q.poll());
}
}
}
/**
* 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();
*/