[92][中等][递归] 反转链表 II
最后更新于
最后更新于
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]输入:head = [5], left = 1, right = 1
输出:[5]# 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, left: int, right: int) -> ListNode:
if left == right:
return head
real_head, new_head, new_next = head, None, None
former, current = None, head
for _ in range(left - 1): # 找到left对应的结点
former = current
current = current.next
def dfs(node, count):
if count == right:
nonlocal new_head, new_next
new_head = node
new_next = node.next
return node
new_node = dfs(node.next, count + 1)
node.next = None
new_node.next = node
return node
new_tail = dfs(current, left)
if former is None:
real_head = new_head
else:
former.next = new_head
new_tail.next = new_next
return real_head