

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


def reverseBetween(head: ListNode, m: int, n: int) -> ListNode:
    cur, tmp_pre, count = head, None, 1
    start, end, pre, nex = None, None, None, None
    while count <= n:
        if count == m:
            start = cur
            pre = tmp_pre
        if count == n:
            end = cur
            nex = end.next
        tmp_pre = cur
        cur = cur.next
        count += 1

    cur, tmp_pre = start, start
    while cur != nex:
        cur = cur.next
        tmp = cur.next
        cur.next = tmp_pre
        tmp_pre = cur
        cur = tmp
    if pre == None:
        head = end
    else:
        pre.next = end
    start.next = nex

    return head


if __name__=='__main__':
    l = [1,2,3,4,5]
    head, pre = None, None
    for each in l:
        cur = ListNode(each)
        if pre:
            pre.next = cur
        else:
            head = cur
        pre = cur

    reverseBetween(head, 2, 4)