public static class TwoQueuesStack {
private Queue<Integer> queue;
private Queue<Integer> help;
public TwoQueuesStack() {
queue = new LinkedList<Integer>();
help = new LinkedList<Integer>();
}
public void push(int pushInt) {
queue.add(pushInt);
}
public int peek() {
if (queue.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
// 队列里面剩一个元素
while (queue.size() != 1) {
help.add(queue.poll());
}
int res = queue.poll();
help.add(res);
// 交换引用,为了在queue中返回的
swap();
return res;
}
public int pop() {
if (queue.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while (queue.size() > 1) {
help.add(queue.poll());
}
int res = queue.poll();
swap();
return res;
}
// 交换引用
private void swap() {
Queue<Integer> tmp = help;
help = queue;
queue = tmp;
}
}
整体思路是:使用两个队列,一个data,另个一个辅助队列help,要实现栈结构,将data中的数据在加入help中,直至data中剩余一个元素,返回这个元素。一直复用这个逻辑,就可以实现栈