原题链接:https://leetcode.com/problems/implement-stack-using-queues/description/
实现如下:
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by clearbug on 2018/4/3.
*
* 使用队列来实现一个栈,这个问题比较有意思,本身我是没有想出实现的,下面的实现是官方解答的方法一:使用两个队列来实现。然后官方方法三提供了
* 一种更简单的使用一种队列来实现的方法,感觉真 nice。
*/
public class MyStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
private int top;
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
top = x;
queue1.offer(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while (queue1.size() > 2) {
queue2.offer(queue1.poll());
}
int oldTop = -1;
if (queue1.size() == 2) {
top = queue1.poll();
queue2.offer(top);
oldTop = queue1.poll();
} else {
oldTop = queue1.poll();
}
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
return oldTop;
}
/** Get the top element. */
public int top() {
return top;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}