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, and return the reversed list.
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Input: head = [5], left = 1, right = 1
Output: [5]
n.1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= nFollow up: Could you do it in one pass?
This approach leverages an extra data structure to reverse the segment of the linked list. We first traverse the list to the position where the reversal starts, collect nodes in an array for the part to be reversed, reverse the array, and finally rebuild the linked list using this array.
Instead of using extra space, this approach manages all operations directly within the list structure. The key is to carefully manage pointers to reverse the sublist in place by detaching and reattaching nodes.