Leetcode 92. 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
, and return the reversed list.
Input:
head
= [1,2,3,4,5]left
= 2right
= 4Output: [1,4,3,2,5]
left
and right
1-based indices?
left
equals right
?
left
equals right
, the list remains unchanged.left
-th node.left
to node right
.left
(let’s call this pre
).left
to right
.This task requires careful pointer manipulation to ensure the list is correctly reformed after reversing the sublist.
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if (head == null || left == right) {
return head;
}
// Dummy node initialization
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
// Move `pre` pointer to the node just before `left`
for (int i = 1; i < left; i++) {
pre = pre.next;
}
// `start` will point to the beginning of the sublist to reverse
ListNode start = pre.next;
// `then` will point to the node that will be reversed
ListNode then = start.next;
// Perform the sublist reversal from `left` to `right`
for (int i = 0; i < right - left; i++) {
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
// Return the modified list
return dummy.next;
}
}
The time complexity of this algorithm is ( O(n) ), where ( n ) is the number of nodes in the linked list. The reason is that each node is visited at most twice: once during the initial traversal to find the left
position and once more during the reversal process.
left
node takes ( O(left) ).left
to right
takes ( O(right - left) ).Thus, the overall complexity simplifies to ( O(n) ).
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?