主要思路是,一个stack1占用来接收正常的压栈,一个stack2用来存放stack1的倒序,当执行pop()操作时,弹出的是stack2的栈顶元素,就会有“先进先出的效果”。
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } stack1.push(node); while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } public int pop() { return stack2.pop(); } public static void main(String[] args) { // TODO Auto-generated method stub Solution s = new Solution(); s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); System.out.println(s.pop()); } }