图解步骤:
代码实现:
package stack1;
import java.util.Stack;
public class Reverse {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
int [] a = {1,2,3};
for (int i = 0; i <a.length ; i++) {
stack.push(a[i]);
}
print(stack);
}
public static void print(Stack<Integer> stack){
reverse(stack);
while (!stack.isEmpty()){
System.out.println(stack.pop());
}
}
public static void reverse(Stack<Integer> stack){
if (stack.isEmpty())
return;
int res1 =getLastPeek(stack);
reverse(stack);
stack.push(res1);
}
public static int getLastPeek(Stack<Integer> stack){
if(stack.isEmpty())
return -1;
int res1 = stack.pop();
if(stack.isEmpty())
return res1;
else {
int res2 = getLastPeek(stack);
stack.push(res1);
return res2;
}
}
}