题目:使用队列实现栈的功能
思路:使用两个队列,比如我要输入(栈低)0,1,2,3,按照栈的性质,输出为3,2,1,0
第一步:初始化两个队列,queue和help;
第二步:把元素存入queue队列中[3,2,1,0] (方向- - ->),此时我需要输出3,具体做法是:
从queue队列中依次弹出0,1,2,将元素0,1,2依次存入help队列中[2,1,0] (方向- - ->),此时queue队列内容为[3],然后弹出queue中的3,此时queue为空
第三步:初始化一个temp队列,用于充当queue与help交换之间的媒介。
package com.inspire.chapter2;
import java.util.LinkedList;
import java.util.Queue;
public class TwoQueueImplementStack {
// 使用两个队列实现栈
public static class TwoQueueStack<T> {
private Queue<T> queue;
private 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> temp = queue;// 此时queue为空
// 重点来了
queue = help;
help = temp;
return ans;
}
}
public static void main(String[] args) {
TwoQueueStack<Integer> stack = new TwoQueueStack<>();
stack.push(0);
stack.push(1);
stack.push(2);
System.out.println(stack.poll());
stack.push(3);
stack.push(4);
System.out.println(stack.poll());
System.out.println(stack.poll());
System.out.println(stack.poll());
System.out.println(stack.poll());
}
}