leetcode 92. reverse-linked-list-ii 反转链表 II python3

时间:2021-2-8

题目地址:https://leetcode-cn.com/problems/reverse-linked-list-ii/

题目难度:Medium

题目描述:

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL


思路1:递归一步一步来

  1. 搞明白反转整个链表的206题
  2. 只反转前n个,特殊处理最后一个节点时需要提前保存他的后继结点
  3. 在考虑递归中如何将值传递进去,如果head的index是1,起止分别是m,n,如果将head.next视为1,起止分别是m-1, n-1

代码段1:通过

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        successor = ListNode()
        def reverseFirstN(head, n): 
        """反转前n个结点""""
            if n == 1:
                global successor
                successor = head.next       # 保留后继结点
                return head
            new_head = reverseFirstN(head.next, n - 1)
            head.next.next = head
            head.next = successor          # 与反转整个链表(head.next = None)不一样的地方
            return new_head
        if m == 1:
            return reverseFirstN(head, n)
        head.next = self.reverseBetween(head.next, m - 1, n - 1)
        return head

总结:

  1. 这我还是整不明白,递归的思路有时候真的难以理解,一定不能跳进递归

后续优化:

迭代 https://leetcode-cn.com/problems/reverse-linked-list-ii/solution/liang-chong-fang-fa-by-powcai/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值