给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
输入: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