队列特点:先进先出
栈特点:先进后出
- 队列转化为栈
假设用户依次存入的数据为1,2,3,4,5;
目标:取出数据顺序变为:5,4,3,2,1;
实现思想:
设置两个队列A、B ,先将所有数据存放到A中,当用户取数据时先将 除5以外的所有数据放入B队列,此时A队列数据为5,B队列数据为1,2,3,4;然后将A出队即可。若继续取出数据,将1,2,3,放入A队列,B剩下4,将B的数据出队即可。往后依次类推。
代码实现:
public static class TwoQueueStack<T> {
public Queue<T> queue;
public Queue<T> help;
public TwoQueueStack() {
queue = new LinkedList<>();
help = new LinkedList<>();
}
public void push(T value) {
queue.offer(value);
}
public T poll() {
while (queue.size() > 1) {
help.offer(queue.poll());
}
T ans = queue.poll();
//引用互换
Queue<T> tmp = queue;
queue = help;
help = tmp;
return ans;
}
public T peek() {
while (queue.size() > 1) {
help.offer(queue.poll());
}
T ans = queue.poll();
help.offer(ans);
// 引用互换
Queue<T> tmp = queue;
queue = help;
help = tmp;
return ans;
}
public boolean isEmpty() {
return queue.isEmpty();
}
}
- 栈转化为队列
假设用户依次存入的数据为1,2,3,4,5;
目标:取出的数据顺便变为:1,2,3,4,5;
实现思想:
设置两个栈A、B , 先将所有数据存到A中,由于栈是先进后出,取出数据是只需要将A{5,4,3,2,1}中的数据依次放到B{1,2,3,4,5}中,然后在出栈就好。
需要注意的是:在将A的数据放到B的时候,必须要将A中的数据全部放入B中,否则就要出现错误。无论取出数据还是存放数据都需要将A中的数据完全放到B中。
代码实现:
public static class TwoStacksQueue {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public TwoStacksQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
// push栈向pop栈倒入数据
private void pushToPop() {
if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
}
public void add(int pushInt) {
stackPush.push(pushInt);
pushToPop();
}
public int poll() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.pop();
}
public int peek() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.peek();
}
}