链表题目,永远的繁琐。。。注意越界情况以及能不能next,头尾处理,最好现在草稿纸上写一遍代码。
/**
* 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;
if(head==NULL)
return NULL;
ListNode* prefirst=NULL;
ListNode* first=head;
ListNode* last=head;
ListNode* lastlast=NULL;
int index=1;
while(m!=index)
{
prefirst=first;
first=first->next;
index++;
}
//find index=m
ListNode* pre=first;
ListNode* now=pre->next;
ListNode* behind=now->next;
while(index!=n)
{
now->next=pre;
pre=now;
now=behind;
if(behind!=NULL)
behind=behind->next;
index++;
}
last=pre;
lastlast=now;
if(prefirst==NULL)
head=last;
else
prefirst->next=last;
first->next=lastlast;
return head;
}
};