题解 | #链表内指定区间反转#
链表内指定区间反转
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 if m == n: # mn相等不用旋转 return head sbnode = ListNode(0) # 搞个哨兵结点,要不然分不开 sbnode.next = head p,l,r,q = sbnode, sbnode, sbnode, sbnode # 初始都指向哨兵 cur = sbnode i = 0 while cur: if i == m-1: p = cur # p表示m之前的那个节点 elif i == m: l = cur # l表示m的节点 elif i == n: r = cur # r表示n的那个节点 elif i == n+1: q = cur # q表示n的后边那个节点 break # 找到q就不用找了 cur = cur.next i += 1 if q == sbnode: # q有可能在链表最后是空的那个点,不会被赋值,所以把他设置成none q = None a = l # a指向l节点 b = a.next # b指向a后 a.next = None # l先指空 while a != r and b: c = b.next # c是b的后继,因为b要返回去指a,所以先让c过去探路 b.next = a # b后头指a a = b # a,b指针后移 b = c l.next = q # 最后链表内部反转完毕,把两头相接处连好 p.next = r return sbnode.next #返回哨兵后继