题解 | #链表内指定区间反转#
链表内指定区间反转
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 head==None or head.next==None:return head late = n-m pi = head for _ in range(late):pi = pi.next pj = head dummy_head = ListNode(0) dummy_head.next = head prej = dummy_head for _ in range(m-1): pi = pi.next pj = pj.next prej = prej.next #反转 nexti = pi.next pre,p = pj,pj.next while(p!=nexti): tmp = p p = p.next tmp.next = pre pre = tmp prej.next = pi pj.next = nexti return dummy_head.next
指定区间翻转,本来以为挺简单就能搞定,但是其实发现有很多细节的地方没注意就会报错,比如边界条件的处理,然后要做一个假头,后面的指针比前面的多走多少步,后面又应该一起走多少步,然后最后翻转的这个操作怎么写才不会错,然后就是debug要快……
#AI面试复盘#