Given the
Output: [1, 4, 3, 2, 5]
Explanation: The sublist from position 2 to 4 ([2, 3, 4]) is reversed to [4, 3, 2].
Output: [5]
We use a single-pass approach. A dummy node is prepended to handle edge cases where reversal starts from the head.
We advance to the node just before position
- Create a
dummy node that points tohead . Setprev = dummy . - Advance
prev exactlyleft - 1 steps so it sits just before the sublist start. - Let
curr = prev.next (the first node of the sublist to reverse). -
Repeat
right - left times: take the node aftercurr , remove it from its position, and insert it immediately afterprev . This effectively reverses the sublist one node at a time. - Return
dummy.next as the new head.
Complexity Analysis:
Time complexity: O(n) where n is the length of the linked list. We traverse the list at most once.
Space complexity: O(1) since we reverse in-place using only a constant number of pointers.