给定一个堆栈【1, 2, 3】,反转为【3, 2, 1】
import java.util.Stack;
public class ReverseStack {
<span style="white-space:pre"> </span>public static void main(String[] args) {
<span style="white-space:pre"> </span>Stack<Integer> stack = new Stack<Integer>();
<span style="white-space:pre"> </span>for (int i = 0; i < 10; i++) {
<span style="white-space:pre"> </span>stack.push(i);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>print(stack);
<span style="white-space:pre"> </span>reverse(stack);
<span style="white-space:pre"> </span>print(stack);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public static void print(Stack<Integer> stack) {
<span style="white-space:pre"> </span>System.out.print("[");
<span style="white-space:pre"> </span>for (int i : stack) {
<span style="white-space:pre"> </span>System.out.print(i + " ");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>System.out.println("]");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public static void reverse(Stack<Integer> stack) {
<span style="white-space:pre"> </span>if (!stack.isEmpty()) {
<span style="white-space:pre"> </span>int i = stack.pop();
<span style="white-space:pre"> </span>reverse(stack);
<span style="white-space:pre"> </span>// add the
<span style="white-space:pre"> </span>addBottom(stack, i);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>private static void addBottom(Stack<Integer> stack, int i) {
<span style="white-space:pre"> </span>if (stack.isEmpty()) {
<span style="white-space:pre"> </span>stack.push(i);
<span style="white-space:pre"> </span>} else {
<span style="white-space:pre"> </span>int e = stack.pop();
<span style="white-space:pre"> </span>addBottom(stack, i);
<span style="white-space:pre"> </span>stack.push(e);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
}