这道题可以用一个queue来实现,但在push方法中创建一个临时的queue,来实现倒置已有元素,这个思路很好。
参考:点击打开链接
class MyStack {
Queue<Integer> queue = new LinkedList<>();
// Push element x onto stack.
public void push(int x) {
Queue<Integer> temp = new LinkedList<>();
while (queue.size() > 0) {
temp.offer(queue.peek());
queue.poll();
}
queue.offer(x);
while (temp.size() > 0) {
queue.offer(temp.peek());
temp.poll();
}
}
// Removes the element on top of the stack.
public void pop() {
queue.poll();
}
// Get the top element.
public int top() {
return queue.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}