题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
#coding:utf-8 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 , m , n ): # write code here if m == n: return head flag = ListNode(0) flag.next = head pre = flag cur = head i = 1 while cur: nex = cur.next if i == m: flag1 = pre flag2 = cur if i > m and i <= n: cur.next = pre if i == n: flag1.next = cur flag2.next = nex pre = cur cur = nex i += 1 return flag.next
头节点需要单独保存一个,用来返回。