比反转整个链表麻烦了一点点。
也是简单的。
/**
* 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 *r, *p, *q;
r = NULL; p = head; q = p->next;
for(int i=1;i<m;i++){
r = p; p = q; q = q->next;
}
ListNode *pre = r;
ListNode *last = p;
int count = n-m;
while(count-->0){
r = p;
p = q;
q = q->next;
p->next = r;
}
last->next = q;
if(pre){
pre->next = p;
return head;
}
if(pre==NULL)
return p;
}
};