Reverse the nodes of a singly linked list between two given positions, inclusive, while keeping the rest of the list unchanged.
Reverse Linked List II
gfgGiven the head of a singly linked list and two positions and , reverse the nodes from position to position in-place, using 1-based indexing.
All nodes outside the range must remain in their original relative order. The sublist between and should be reversed as a contiguous segment, and the final list should be returned.
Input Format
- A singly linked list
head - Two integers
leftandrightwith1 <= left <= right <= n
The list nodes are provided in order.
Output Format
Return the head of the modified linked list after reversing the nodes in the specified range.
Constraints
- The list contains at least one node
- Reversal must be done by changing links between nodes; node values should not be modified as a substitute
- Use extra space if possible
Example 1
Input
head = [1,2,3,4,5], left = 2, right = 4
Output
[1,4,3,2,5]
Explanation
The sublist [2,3,4] is reversed to [4,3,2], while the rest of the list stays in place.
Example 2
Input
head = [5], left = 1, right = 1
Output
[5]
Explanation
A single-node sublist is unchanged.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.