classSolution:defreverseBetween(self, head: Optional[ListNode], left:int, right:int)-> Optional[ListNode]:
dummy = ListNode(next=head)
cur = dummy
for i inrange(left-1):
cur = cur.next
begin = cur #保存翻转的前一个节点
pre =None#反转链表
cur = cur.nextfor i inrange(right-left+1):
temp = cur.next
cur.next= pre
pre = cur
cur = temp
#for循环结束后pre指向反转后的头节点,cur指向未反转的第一个节点
begin.next= pre #前节点拼接while(pre.next):
pre = pre.next
pre.next= cur #后节点拼接return dummy.next