Reverse Linked List II
You're given the head of a singly linked list along with two 1-indexed positions, left and right. Reverse only the segment of nodes between those positions, inclusive, leaving the rest of the list untouched, and return the head.
Input Format
Implement reverseBetween(head, left, right). Inputs below show JavaScript function arguments; there is no stdin parsing.
Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.
Returned list heads are displayed as value arrays; a null head is [].
Sample Input and Output
Example 1 ยท Run Sample
Input
head = [1,2,3,4,5]
left = 2
right = 4 Output
[1,4,3,2,5] Example 2
Input
head = [1]
left = 1
right = 1 Output
[1] Constraints
- 1 <= n <= 500
- -500 <= Node.val <= 500
- 1 <= left <= right <= n
Test Cases (2)
Case 1
Args: [[1,2,3,4,5],2,4]
Expected: [1,4,3,2,5]
Case 2
Args: [[1],1,1]
Expected: [1]
Topics
In-Place Reversal
function reverseBetween(head, left, right) {
const dummy = {next: head};
let prev = dummy;
for (let i = 0; i < left - 1; i++) prev = prev.next;
let curr = prev.next;
for (let i = 0; i < right - left; i++) {
const next = curr.next;
curr.next = next.next;
next.next = prev.next;
prev.next = next;
}
return dummy.next;
}Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.