/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m == n) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy, curr = head;
ListNode revPrev = dummy;
for(int i = 1; i <= n; i++) {
if(i == m) {
revPrev = prev;
}
if(i <= n && i > m) {
prev.next = curr.next;
curr.next = revPrev.next;
revPrev.next = curr;
curr = prev;
}
prev = curr;
curr = curr.next;
}
return dummy.next;
}
}
Time: O(n)
Space: O(1)