首页 > 其他 > 详细

逆序一个栈,不申请额外空间,只使用递归函数

时间:2020-09-14 09:33:30      阅读:75      评论:0      收藏:0      [点我收藏+]

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;
}
}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */

逆序一个栈,不申请额外空间,只使用递归函数

原文:https://www.cnblogs.com/laydown/p/13664746.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!