时间: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:递归一步一步来
- 搞明白反转整个链表的206题
- 只反转前n个,特殊处理最后一个节点时需要提前保存他的后继结点
- 在考虑递归中如何将值传递进去,如果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
总结:
- 这我还是整不明白,递归的思路有时候真的难以理解,一定不能跳进递归
后续优化:
迭代 https://leetcode-cn.com/problems/reverse-linked-list-ii/solution/liang-chong-fang-fa-by-powcai/