import java.util.Stack; /** * push 先从第二个栈倒转过来,然后push, 然后再倒转到第二个栈。 * pop 直接从第二个栈获取数据。 */ public class TwoStackQueueTest { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.clear(); while (stack2.size() > 0) { stack1.push(stack2.pop()); } stack1.push(node); stack2.clear(); while (stack1.size() > 0) { stack2.push(stack1.pop()); } } public int pop() { return stack2.pop(); } public static void main(String[] args) { TwoStackQueueTest test = new TwoStackQueueTest(); test.push(1); test.push(2); System.out.println(test.pop()); System.out.println(test.pop()); } }