class ListNode: def __init__(self, val = 0, next = None): self.val = val self.next = next class Solution: def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: cnt = 0 l = [] true_head = ListNode() true_head.next = head true_end = ListNode() cur = head while cur.next != None: cur = cur.next cur.next = true_end cur = true_head while cur != None: if cnt >= left - 1 and cnt <= right + 1: l.append(cur) cur = cur.next cnt += 1 for ind in range(len(l), 0, -1): l[ind].next = l[ind-1]