LeetCode 92: Reverse Linked List II Solution
Master LeetCode problem 92 (Reverse Linked List II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
92. Reverse Linked List II
Problem Explanation
Explanation:
To solve this problem, we can follow these steps:
- Traverse the linked list until we reach the left-th node.
- Reverse the nodes from left to right by changing the pointers accordingly.
- Reconnect the reversed sublist back to the original list.
- Return the modified linked list.
Time complexity: O(n) - we only traverse the list once Space complexity: O(1) - we use constant extra space
:
Solution Code
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if (head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
}
ListNode start = pre.next;
ListNode then = start.next;
for (int i = 0; i < right - left; i++) {
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
return dummy.next;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 92 (Reverse Linked List II)?
This page provides optimized solutions for LeetCode problem 92 (Reverse Linked List II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 92 (Reverse Linked List II)?
The time complexity for LeetCode 92 (Reverse Linked List II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 92 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 92 in Java, C++, or Python.