题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head, m, n):
if not head or m == n:
return head
dummy = ListNode(0)
dummy.next = head
pre = dummy
# Move `pre` to the element right before the reversal starts
for _ in range(m - 1):
pre = pre.next
# Reverse the sublist from m to n
reverse = None
curr = pre.next
for _ in range(n - m + 1):
next_temp = curr.next
curr.next = reverse
reverse = curr
curr = next_temp
# Connect the end of the reversed sublist to the remaining part of the list
pre.next.next = curr
# Connect the start of the reversed sublist to the initial part of the list
pre.next = reverse
return dummy.next