今天看到一个算法的题目用递归实现栈内数据的逆序,就是把栈内的数据从上到下颠倒过来。
先思考一下这个难度只有2个星的题目自己能不能写出来。。。。。。。。
答案的代码我一开始都没有看明白。上代码
public static void reverse(Stack<Integer> stack) {
if (stack.isEmpty()) {
return;//返回只结束当前的方法
}
int i = getLastAndRemove(stack);
reverse(stack);
stack.push(i);
}
//获取栈底的元素并移除
public static Integer getLastAndRemove(Stack<Integer> stack) {
Integer result = stack.pop();
if (stack.isEmpty()) {
return result;//返回只结束当前的方法
} else {
Integer last = getLastAndRemove(stack);
stack.push(result);
return last;//返回只结束当前的方法
}
}
让我们先复习一下递归:递归就是自己调用自己
注意事项:一定要有出口(一般和if条件语句配合使用)
次数不能太多(太多会有栈溢出的风险)
优点:比循环效率高
我们来分析一个比较熟悉的递归 计算n的阶乘
public static int get(int n){
if(n==1){
return 1;
}
return n * get(n-1);
}
1 n=3假定 3 * get(2)
3 * 2 * get(1)
3 * 2 * 1
这就是执行的步骤
递归在运算的时候需要注意的点:
return 返回的时当前的方法(当前的方法会弹栈)不会结束整个方法
执行的每个方法都会压栈,压栈后的方法执行完后就会弹栈然后继续执行外层的方法。
我们分析一下这个
//获取栈底的元素并移除
public static Integer getLastAndRemove(Stack<Integer> stack) {
1. Integer result = stack.pop();
2. if (stack.isEmpty()) {
3. return result;//返回只结束当前的方法
} else {
4. Integer last = getLastAndRemove(stack);
5. stack.push(result);
6. return last;//返回只结束当前的方法
}
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
getLastAndRemove(stack);
}
4行很重要
第一轮进 每次执行到4就会递归
当stack为空的时候第一轮进 结束 开始第二轮的出
出的时候执行的时每一轮进的时候未执行完的代码即5.6
出的时候把每一轮进的时候剩余的未执行的5.6执行一遍
这个地方实在时太难描述了 大家想不明白就debug看吧
欢迎大家关注我的微信公众号 您的关注就是我不懈的动力