leetcode反转链表

描述

示例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就需要执行。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值