Leetcode 92. Reverse Linked List II
You are 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.
Example:
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Constraints:
n
.1 <= n <= 500
.-500 <= Node.val <= 500
.1 <= left <= right <= n
.Q: What should be returned if left
is equal to right
?
A: If left
is equal to right
, the list remains unchanged since there’s no range to reverse.
Q: Are the node values unique? A: Node values are not necessarily unique.
Q: Do we have to handle empty lists? A: No, according to the constraints we assume that the number of nodes is at least 1.
left
-th node.struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if (!head) return nullptr;
// Create a dummy node to simplify operations
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* prev = dummy;
// Move `prev` to the node just before the `left`-th node
for (int i = 1; i < left; ++i) {
prev = prev->next;
}
// `start` will point to the `left`-th node
ListNode* start = prev->next;
// `then` will point to the `left+1`-th node
ListNode* then = start->next;
// Reverse the sublist from `left` to `right`
for (int i = 0; i < right - left; ++i) {
start->next = then->next;
then->next = prev->next;
prev->next = then;
then = start->next;
}
return dummy->next;
}
};
O(n)
where n
is the number of nodes in the linked list. We traverse the list to reach the left
-th node and perform a constant amount of operations for each node in the sublist to be reversed.O(1)
as we are reversing the linked list in place and only using a few auxiliary pointers.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?