/**
* 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) {
ListNode * res=head;
if(m==n) return res;
int i=1;
ListNode * pre=NULL; //记录待反转链表的前驱,注意,带反转链表从头开始的情况,没有前驱
ListNode * left; //记录待反转链表的开始
if(m>1) {
pre=head;
while(i<m-1){
pre=pre->next;
i++;
}
left = pre->next;
}
else left = head;
i=0;
ListNode *post=left; //记录待反转链表的后继,注意赋初值为left,而不是head,pre之类的
while(i<n-m+1){
post=post->next;
i++;
}
ListNode *right=reverselist(left,n-m+1); //记录待反转链表的结束
if(pre) pre->next =right;
else res = right;
while(right->next){
right=right->next;
}
right->next=post;
return res;
}
//把head开始长度为l的拉链,反转
ListNode* reverselist(ListNode* head,int l)
{
ListNode * pre=NULL;
ListNode * cur=head;
ListNode * post=NULL;
int i=0;
while(i<l){
post = cur->next;
cur->next = pre;
pre = cur;
cur = post;
i++;
}
return pre;
}
};