题解 | #链表内指定区间反转#
链表内指定区间反转
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: # write code here # total = 0 # tmp = head # while tmp: # total+=1 # tmp = tmp.next cur = head pre = None idx = 0 while cur: tmp = cur.next if m==n: return head if (idx + 1 == m) and (m==1): break0 = cur if idx + 2 == m: break1 = cur break2 = cur.next if idx < m: pre = cur else: cur.next = pre pre = cur if idx + 1 == n: if m==1: break0.next = tmp return pre else: break1.next = cur break2.next = tmp return head cur = tmp idx += 1