思路:
Queue的特性是先进先出
Stack的特性是先进后出
如何让进入Queue的数据后出呢?
反转整条队列,也就是每进入一个数据,对整个队列进行反转
如何反转?
1.使用另一个队列辅助反转
2.原地反转
- 使用另一个队列辅助反转
class MyStack {
/** Initialize your data structure here. */
//outQueue作为辅助队列,同时保存已经反转好的队列
private Queue<Integer> inQueue;//输入队列
private Queue<Integer> outQueue;//输出队列
public MyStack() {
inQueue=new LinkedList<>();
outQueue=new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
inQueue.offer(x);//加入输入队列
//加入的数据要先出,所以我们把已经反转好的数据加到后面
while(!outQueue.isEmpty()){
inQueue.offer(outQueue.poll());
}
//此时反转好的数据保存在inQueue中,交换两者即可
Queue<Integer> temp=inQueue;
inQueue=outQueue;
outQueue=temp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return outQueue.poll();
}
/** Get the top element. */
public int top() {
return outQueue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return outQueue.isEmpty();
}
}
- 原地反转
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
int n = queue.size();
//插入之前,queue中的数据已经反转好(因为是一个一个加,每次加都会反转)
queue.offer(x);//插入数据
//之后为了保证其先出,将其前面的数据移动到后面
for (int i = 0; i < n; i++) {
queue.offer(queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}