Reverse Linked List II
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 (1-indexed) and return the head. Do it in one pass.
Open official problem prompt ↗Reverse a contiguous run of nodes between two 1-indexed positions in a single pass without allocating new nodes.
Like reversing a stretch of beads on a string by repeatedly sliding the bead just ahead back to the start of the stretch, one at a time.
- Input
- head = [1,2,3,4,5], left = 2, right = 4
- Output
- [1,4,3,2,5]
- Why
- Reversing positions 2 through 4 (values 2,3,4) gives 4,3,2, leaving the ends 1 and 5 in place.
The number of nodes is n1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n