Solving·27 Aug
Reverse Linked List II
DifficultyMedium
PatternIn place reversal LinkedList
TrackDSA
tl;dr
Given a singly linked list with `n` nodes and two positions, `left` and `right`, the objective is to reverse the nodes of the list from `left` to `right`. Return the modified list.
full write-up
Statement
Given a singly linked list with n nodes and two positions, left and right, the objective is to reverse the nodes of the list from left to right. Return the modified list.
Constraints
- 1 ≤
n≤ 500 - −5000 ≤
node.data≤ 5000 - 1 ≤
left≤right≤n
Examples
Example 1
Input:
head = [1, 2, 3, 4, 5]
left = 2, right = 4
Explanation:
The nodes from position 2 to 4 are [2, 3, 4]. Reversing them gives [4, 3, 2]. The rest of the list stays in place.
Output: [1, 4, 3, 2, 5]
Example 2
Input:
head = [5, 1, 3, 8]
left = 1, right = 4
Explanation:
The nodes from position 1 to 4 cover the entire list [5, 1, 3, 8]. Reversing the whole list gives [8, 3, 1, 5].
Output: [8, 3, 1, 5]