//两个栈实现队列
public class Test{ Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public static void main(String[] args) { Test test = new Test(); test.push(1); test.push(2); test.push(3); System.out.println(test.pop()); System.out.println(test.pop()); test.push(4); System.out.println(test.pop()); test.push(5); System.out.println(test.pop()); System.out.println(test.pop()); } //原理:栈是先进后出,队列是先进先出。 public void push(int node) { stack1.add(node); } public int pop() { //判断stack2是否为空,如果不为空则直接出栈,为空则进行stack1出栈,stack2进栈,最后返回stack2出栈 if (!stack2.isEmpty()) { return stack2.pop(); } //将stack1中的值都进入到stack2 while (!stack1.isEmpty()) { stack2.add(stack1.pop()); } return stack2.pop(); }} 输入:1,2,3进栈,出栈,出栈,4进栈,出栈,5进栈,出栈 输出:1,2,3,4,5