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.
Copying the values into an array, reversing that slice, and writing them back works. But it uses extra space, and we can relink in place.
Walk a pointer, previous, to the node just before position left. Then, again and again, take the node after current and move it to the front of the section. Repeat right minus left times.
Fix previous before the section and keep moving the next node to the front. Current slides to the back by itself.
Run the animation above on your own input, or watch the 1:12 video explanation of Reverse Linked List II with a dry run and Java code.