Reverse only the nodes from position left to position right. Positions start at 1, and the rest of the list stays in place.
DSA Animator › DSA Revision › Linked List › Reverse Linked List II
Remember: fix previous before the section and keep moving the next node to the front. Current slides to the back by itself. The video solves Reverse Linked List II (LeetCode 92, Medium) with the Pointer Reversal pattern from the Linked List topic, and you can replay every step in the interactive Reverse Linked List II animation.
Reverse only the nodes from position left to position right. Positions start at 1, and the rest of the list stays in place.
For 1, 2, 3, 4, 5 with left 2 and right 4, the result is 1, 4, 3, 2, 5.
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.
Previous stops at 1, and current is 2. Move 3 to the front, after 1, giving 1, 3, 2, 4, 5. Move 4 to the front, giving 1, 4, 3, 2, 5. Two moves were needed, so we are done.
In code, use a dummy head and move previous left minus 1 steps. In a loop, take the node after current, unlink it, and insert it right after previous. Return dummy dot next, so it's one pass and O of 1 space.
Remember: fix previous before the section and keep moving the next node to the front. Current slides to the back by itself.