Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
classListNode: def__init__(self, val: int = 0, next: Optional["ListNode"] = None): self.val = val self.next = next
classSolution: defreverseBetween( self, head: Optional["ListNode"], left: int, right: int ) -> Optional["ListNode"]: ifnot head or left >= right: return head dummy = ListNode(-1, head) start, end = dummy, dummy left_node = None count = 1 convert_flag = False while head: ifnot convert_flag: if count == left: start = end end, left_node = head, head convert_flag = True else: end = head head = head.next else: temp = head.next if count == right: head.next = end left_node.next = temp if start: start.next = head break else: head.next = end end = head head = temp count += 1 return dummy.next