import java.util.Stack;
/**
* 逆序一个栈,不申请额外空间,只使用递归函数
*/
public class RevertStack {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
reverse(stack);
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
private static void reverse(Stack<Integer> stack) {
if (stack == null || stack.isEmpty()) {
return;
}
Integer last = getAndRemoveLast(stack);
reverse(stack);
stack.push(last);
}
private static Integer getAndRemoveLast(Stack<Integer> stack) {
Integer result = stack.pop();
if (stack.isEmpty()) {
return result;
} else {
Integer last = getAndRemoveLast(stack);
stack.push(result);
return last;
}
}
}
/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */