You get the head of a singly linked list and two whole numbers left and right, with left <= right. Count positions from 1 at the head. Reverse the order of the nodes from position left through position right, keep every other node where it is, and return the head of the rearranged list.
Rearrange the nodes themselves rather than rewriting the values stored in them. Try to do it in a single pass over the list.
The nodes in positions 2 to 5 come out in reverse order. 9 and 3 sit outside that range and don't move.
The range covers the whole list, so the whole list is reversed and the old last node becomes the head.
A range of one node has nothing to reverse.
Constraints
n nodes, where 1 <= n <= 1000.-1000 <= Node.val <= 10001 <= left <= right <= nFind the node just before position left; a dummy node in front of the head covers left = 1. Nothing before that node or after position right moves.
Split the list into three pieces: the nodes before position left, the run from left to right, and the nodes after right. The first and last pieces don't change at all. Only the middle run flips, and then it has to be stitched back in at both ends.
Time O(n)Space O(1)
The full walkthrough and code are part of Premium