题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 # @param m int整型 # @param n int整型 # @return ListNode类 # class Solution: def reverseBetween(self , head: ListNode, m: int, n: int) -> ListNode: if m == n: return head tmp_head = ListNode(-1) # 添加一个头,防止m=1,最后去掉 tmp_head.next = head break_point = tmp_head for i in range(m-1): break_point = break_point.next # 断点 new_tail = break_point.next # 反转区间的新尾部 cur = new_tail # 指针、 per = cur.next for i in range(n-m): # 需要n-m次反转 tmp = per.next per.next = cur cur = per per = tmp new_tail.next = per break_point.next = cur head = tmp_head.next return head