/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(m == n){
return head;
}
ListNode dummy(-1);
ListNode* prev = &dummy;
dummy.next = head;
ListNode* fast = prev, *slow = prev;
for(int i = 1; i < m; ++i){ //fast points to the (m-1)-th pointer of the linked list
fast = fast->next;
}
if(fast->next->next == NULL){
return head;
}
ListNode *tail = fast; //tail: (m - 1)-th pointer of the linked list
ListNode* tmphead = fast->next; //tmphead: m-th pointer of the linked list
prev = fast; //(m - 1)-th pointer of the linked list
fast = fast->next; //fast points to the m-th pointer of the linked list
for(int i = m; i <= n; ++i){
ListNode* tmpnext = fast->next; //(i + 1)-th pointer of the linked list
fast->next = prev;
prev = fast;
fast = tmpnext;
}
//fast: (n + 1)-th pointer of the linked list
tail->next = prev;
tmphead->next = fast;
return dummy.next;
}
};
(7 ms solution, one pass and O(1) space)