package arithmetic; import java.util.Stack; public class TwoStacksQueue { public Stack<Integer> stackPush; public Stack<Integer> stackPop; public TwoStacksQueue() { stackPush = new Stack<>(); stackPop = new Stack<>(); } public void pushToPop() { //pop栈为空时才可以导入 if (stackPop.isEmpty()) { //只要导入就需要将push栈全部导入pop栈 while (stackPush != null) { stackPop.push(stackPush.pop()); } } } public void add(int value) { stackPush.push(value); pushToPop(); } public int poll() { if (stackPop.isEmpty() && stackPush.isEmpty()) { 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(); } public static void main(String[] args) { TwoStacksQueue test = new TwoStacksQueue(); test.add(1); test.add(2); test.add(3); System.out.println(test.peek()); System.out.println(test.poll()); System.out.println(test.peek()); System.out.println(test.poll()); System.out.println(test.peek()); System.out.println(test.poll()); } }