class Solution(object):def reverseBetween(self, head, left, right):""":type head: ListNode:type left: int:type right: int:rtype: ListNode""" right = right -1left = left -1while( right-left>=0 ):print(right-left)# 左侧节点l = headfor i in range(left):l = l.next# 右侧节点r = headfor i in range(right):r = r.next# print(l.val, r.val)l.val, r.val = r.val, l.valright = right-1left = left+1print(head)return head
上面的方法其实有那么些问题,更ok的应该是下面这种
class Solution:def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:# 设置 dummyNode 是这一类问题的一般做法dummy_node = ListNode(-1)dummy_node.next = headpre = dummy_nodefor _ in range(left - 1):pre = pre.nextcur = pre.nextfor _ in range(right - left):next = cur.nextcur.next = next.nextnext.next = pre.nextpre.next = nextreturn dummy_node.next