Reverse Linked List II
Reverse a sublist of nodes from position left to right in a single pass in O(n) time and O(1) space.
01The problem
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.
Positions are 1-indexed. The reversal must be done in a single pass and in place.
| Input | Output | Why |
|---|---|---|
[1, 2, 3, 4, 5], left = 2, right = 4 | [1, 4, 3, 2, 5] | Nodes at indices 2 through 4 (2, 3, 4) become 4, 3, 2 |
[5], left = 1, right = 1 | [5] | Single node range remains unchanged |
[1, 2], left = 1, right = 2 | [2, 1] | Reversing entire two-node list |
[1, 2, 3], left = 1, right = 3 | [3, 2, 1] | Reversal starting from the head node |
Constraints: 1 to 500 nodes, node values between -500 and 500, 1 <= left <= right <= n.
Loading the rest of the lesson…