92. 反转链表 II - 力扣(LeetCode)
# 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: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:# 如果链表为空,或者不需要反转,直接返回if not head or left == right:return head# 创建虚拟头节点,以简化操作(处理 left 为 1 的情况)dummy = ListNode(0)dummy.next = headprev = dummy# 1. 找到 left 节点的前一个节点for _ in range(left - 1):prev = prev.next# 2. 开始反转curr = prev.next # left 节点next_node = None # 用于存储临时的下一个节点for _ in range(right - left + 1):next_temp = curr.nextcurr.next = next_nodenext_node = currcurr = next_temp# 3. 连接反转后的部分prev.next.next = curr # 连接到 right 节点后的部分prev.next = next_node # 连接反转部分的头节点return dummy.next