题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
# class ListNode: # from numpy import right_shift # 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: # write code here # 新建一个链表 连接上主链表 new_list = ListNode(-1) new_list.next = head # 获取主链表中需要反转的内容 生产新链表 # 剔除左边 left_list = new_list for i in range(m - 1): left_list = left_list.next # return left_list # 剔除右边 right_list = left_list for i in range(n - m + 1): right_list = right_list.next left_node = left_list.next succ = right_list.next left_list.next = None right_list.next = None # 反转链表 prev = None current_list = left_node while current_list: current_node = current_list.next current_list.next = prev prev = current_list current_list = current_node # 拼接链表 left_list.next = prev left_node.next = succ return new_list.next