/**
* 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 *pre=NULL;
ListNode *median=NULL;
ListNode *pos=NULL;
ListNode *p=head;
for(int i=1;i<m&&p;i++)
{
if(!pre)
{
pre=p;
}
else
{
pre->next=p;
pre=pre->next;
}
p=p->next;
}
ListNode *firstmedian=NULL;
for(int i=m;i<=n&&p;i++)
{
if(!median)
{
median=p;
p=p->next;
median->next=NULL;
firstmedian=median;
}
else
{
ListNode *temp=p->next;
p->next=median;
median=p;
p=temp;
}
}
if(pre) pre->next=median;
if(firstmedian) firstmedian->next=p;
if(!pre)
head=median;
return head;
}
};
* 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 *pre=NULL;
ListNode *median=NULL;
ListNode *pos=NULL;
ListNode *p=head;
for(int i=1;i<m&&p;i++)
{
if(!pre)
{
pre=p;
}
else
{
pre->next=p;
pre=pre->next;
}
p=p->next;
}
ListNode *firstmedian=NULL;
for(int i=m;i<=n&&p;i++)
{
if(!median)
{
median=p;
p=p->next;
median->next=NULL;
firstmedian=median;
}
else
{
ListNode *temp=p->next;
p->next=median;
median=p;
p=temp;
}
}
if(pre) pre->next=median;
if(firstmedian) firstmedian->next=p;
if(!pre)
head=median;
return head;
}
};