Reverse Linked List II
Given the head of a singly linked list and two 1-based positions left <= right, reverse the nodes from position left to position right inclusive, and return the head of the modified list. Nodes outside that range keep their order.
Lists are shown in array notation for readability — reverseBetween([1,2,3,4,5], 2, 4) reverses the middle three to give [1,4,3,2,5].
Example cases
- middle reversedin head = [1,2,3,4,5]12345nullleft = 2right = 4out [1,4,3,2,5]14325nullPositions 2..4 (2,3,4) reverse to 4,3,2.
- single nodein head = [5]5nullleft = 1right = 1out [5]5nullA one-node range is unchanged.
- whole listin head = [1,2,3,4,5]12345nullleft = 1right = 5out [5,4,3,2,1]54321null
Constraints
- The number of nodes in the list is in the range [1, 500].
- -500 <= Node.val <= 500
- 1 <= left <= right <= n
head =
[1,2,3,4,5]
left =
2
right =
4