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 (1-indexed), and return the reversed list.
head = [1,2,3,4,5], left = 2, right = 4[1,4,3,2,5]head = [5], left = 1, right = 1[5]head = [1,2,3,4,5], left = 1, right = 5[5,4,3,2,1]dummy → head; set prev = dummyprev to position left−1 (loop i=1..left-1)curr = prev.next — anchor for the tail of the reversed sublistright−left times: nxt = curr.next → insert nxt right after prev (front-insertion)dummy.next
Each iteration grabs the node right after curr (call it nxt) and moves it
to the front of the growing reversed sublist — just after prev:
curr.next = nxt.next — skip nxt from its place
nxt.next = prev.next — nxt will point to old sublist head
prev.next = nxt — nxt is the new sublist head
After right−left moves the entire sublist is reversed in-place.
curr naturally ends up at the tail because it never moves — only its successor changes.