描述
示例1
输入:
{1,2,3}
复制返回值:
{3,2,1}
代码详解
描述:之前看的递归解析讲的都不是太明白,所以做一个完整解析版
import sys
sys.setrecursionlimit(100000)
class Solution:
def ReverseList(self, head:ListNode)->ListNode:
if head is None or head.next is None:
return head
newHead = self.ReverseList(head.next)
head.next.next = head
head.next = None
return newHead
我们拿{3,2,1}举例
先看递归代码:
def ReverseList(self, head:ListNode)->ListNode:
if head is None or head.next is None:
return head
newHead = self.ReverseList(head.next)
head.next.next = head
head.next = None
return newHead
先判断,空链表返回自己,否则开始递归,递归初始条件是head.next也就是{2,1},此时判断非空,继续递归{1},判断为空,返回newHead={1},这里是递归了两次,我们展开说这两次的情况:
递归过程:{2,1}->{1}->{1}
递归回溯过程:{2,1}->{1,2,None},{3,1,2,None}->{1,2,3,None}(这里考虑一下两行代码)
head.next.next = head
head.next = None
# 递归回溯
# 第一步{2,1} -> {1,2}
# 第二步{3,{1,2}}->{1,2,3},展开即是3->{1,2}->3->None=>{1,2,3}
解释:递归就是不断执行,知道return,递归回溯就是追溯递归函数之外的部分,只要没有return就需要执行。