题目要求使用Queue来实现Stack,我们都知道Queue是FIFO,而Stack是FILO,为了解决这个问题,我们只要在add元素进Queue的时候把之前加进去的元素都poll出来然后再重新add进Queue即可,这样就是实现了FILO的操作。具体的函数实现见下面:
整体的代码如下:
class MyStack {
Queue<Integer> queue;
public MyStack(){
queue = new LinkedList<Integer>();
}
// Push element x onto stack.
public void push(int x) {
queue.offer(x);
for(int i = 0; i < queue.size() - 1; i++){
queue.offer(queue.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();
}
}
知识点:
1. 这种使用Stack实现Queue的问题和使用Queue实现Stack的问题都是非常容易考的问题,把它们的解题方法记一下