/**
* 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 < 1 || m >= n || !head) {
return head;
}
ListNode *newNode = new ListNode(0);
newNode->next = head;
head = newNode;
for (int i = 0; i < m - 1; i++) {
head = head->next;
}
ListNode *pre = head->next, *cur = pre->next;
for (int i = 0; i < n - m; i++) {
ListNode *next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
head->next->next = cur;
head->next = pre;
return newNode->next;
}
};