题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseBetween(self , head: ListNode, m: int, n: int) -> ListNode: dummy_head = ListNode(0) dummy_head.next = head # Move prev to the node before the reversal range prev = dummy_head for _ in range(m - 1): prev = prev.next # Initialize curr to the first node in the reversal range curr = prev.next # Reverse the nodes in the reversal range for _ in range(n - m): temp = curr.next curr.next = temp.next temp.next =prev.next prev.next = temp return dummy_head.next