package class03; import java.util.Stack; public class Code06_TwoStacksImplementQueue { public static class TwoStacksQueue { public Stack stackPush; public Stack stackPop; public TwoStacksQueue() { stackPush = new Stack(); stackPop = new Stack(); } // 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(); } } 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()); } }