Introduction#

递归(recursion)是一种计算机科学中常用的技术,它是指在函数定义中使用函数自身的方法。简单来说,递归是一种自我调用的算法。

下面是一个使用递归计算阶乘的示例:

 1def factorial(n):
 2    if n == 0:
 3        return 1
 4    else:
 5        return n * factorial(n - 1)
 6
 7
 8r = factorial(4)
 9
10print(r)

LeetCode 练习#

https://leetcode.com/problems/reverse-linked-list/ 递归法解决反转链表

 1# Definition for singly-linked list.
 2# class ListNode:
 3#     def __init__(self, val=0, next=None):
 4#         self.val = val
 5#         self.next = next
 6from typing import Optional
 7
 8
 9class ListNode:
10    def __init__(self, val=0, next=None):
11        self.val = val
12        self.next = next
13
14
15class Solution:
16    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
17
18        if not head:
19            return None
20
21        new_head = head
22        if head.next:
23            new_head = self.reverseList(head=head.next)
24            head.next.next = head
25
26        head.next = None
27        return new_head
28
29
30s = Solution()
31head = ListNode(
32    val=1,
33    next=ListNode(
34        val=2, next=ListNode(val=3, next=ListNode(val=4, next=ListNode(val=5)))
35    ),
36)
37s.reverseList(head=head)