算法通关村-----一图理解递归

递归的本质

递归的本质是方法调用,自己调用自己,系统为我们维护了不同调用之间的保存和返回功能。

递归的特征

执行范围不断缩小,这样才能触底反弹

终止判断在递归调用之前

如何写递归

以n的阶乘为例

第一步 从小到大递推

n=1 f(1)=1

n=2 f(2) = 2*f(1)=2

n=3 f(3) = 3*f(3)=6

...

f(n) = n*f(n-1)

第二步 分情况讨论 明确结束条件

当n=1时,f(n)=1

第三步 组合出完整方法

java 复制代码
public int f(n){
	if(n==1){
		return 1;
	}
	return n*f(n-1);
}

如何看懂递归代码

一图理解递归

链表反转

问题描述

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。详见leetcode206

问题分析

之前我们已经使用过两种方式来进行链表反转。分别是虚拟头节点的方式和直接反转的方式,链表反转也可以通过递归来实现

代码实现

直接反转

java 复制代码
public static LinkedNode reverse2(LinkedNode head){
    LinkedNode pre = null;
    LinkedNode current = head;
    while (current!=null){
        LinkedNode next = current.next;
        current.next = pre;
        pre = current;
        current = next;
    }
    return pre;
}

使用虚拟头节点进行反转

java 复制代码
public LinkedNode reverse(LinkedNode head){
    LinkedNode vhead = new LinkedNode(-1);
    vhead.next = head;
    LinkedNode current = head;
    while(current!=null){
        LinkedNode next = current.next;
        current.next = vhead.next;
        vhead.next = current;
        current = next;
    }
    return vhead.next;
}

使用递归进行反转

java 复制代码
public ListNode reverse(ListNode head) {
    if(head==null||head.next==null){
        return head;
    }
    ListNode node = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return node;
}
相关推荐
88号技师18 分钟前
2026年4月一区SCI-狒狒优化算法Baboon optimization algorithm-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
此生决int26 分钟前
快速复习之数据结构篇——二叉树(二)
数据结构
凯瑟琳.奥古斯特36 分钟前
BFS解力扣1654最短跳跃次数
数据结构·算法·广度优先
sg_knight36 分钟前
第一次用 OpenClaw,我让它 3 分钟写了个小工具
算法·llm·agent·ai编程·openclaw
m0_6294947336 分钟前
LeetCode 热题 100-----23.反转链表
数据结构·算法·leetcode·链表
炸膛坦客42 分钟前
嵌入式 - 数据结构与算法:(1-10)排序算法 - 冒泡排序(Bubble Sort)
算法·排序算法
无限进步_1 小时前
【C++】从红黑树到 map 和 set:封装设计与迭代器实现
开发语言·数据结构·数据库·c++·windows·github·visual studio
Hello eveybody1 小时前
介绍一下动态树LCT(Python)
开发语言·python·算法
不穿铠甲的穿山甲1 小时前
MMR最大边际相关性
算法
handler011 小时前
速通蓝桥杯省一:二分算法
c语言·开发语言·c++·笔记·算法·职场和发展·蓝桥杯