1# Definition for singly-linked list.2# class ListNode:3# def __init__(self, val=0, next=None):4# self.val = val5# self.next = next6class Solution:7def reverseBetween(8self, head: Optional[ListNode], left: int, right: int9) -> Optional[ListNode]:10# revrese api11def reverse(start, end):12prev = None13cur = start14while prev != end:15nextNode = cur.next16cur.next = prev17prev = cur18cur = nextNode19return prev2021if not head or not head.next or right <= left:22return head2324start, end = head, head25node, afterRight = 0, 02627# At the begining28if left == 1:29# start index30inc = left - 131while inc > 0:32start = start.next33inc -= 134# end index35inc = right - 136while inc > 0:37end = end.next38inc -= 139afterRight = end.next40reverse(start, end)41head = end42else: # Left other then begining43# start index44inc = left - 245while inc > 0:46start = start.next47inc -= 148# end index49inc = right - 150while inc > 0:51end = end.next52inc -= 153afterRight = end.next54begin = start # node before left55start = start.next56reverse(start, end)57begin.next = end5859# If their's ll chain left agter right chain it to the updated ll60if afterRight:61start.next = afterRight6263return head646566"""67TC : O(n)68Sc : O(1)6970"""