Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m =
2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy
the following condition:
1 ? m ? n ?
length of list.
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(m>=n)
return head;
ListNode *L=new ListNode(0);
L->next=head;
int count=1;
ListNode *p,*tear,*cur,*next;
p=L,cur=L->next;
for( ; cur ; cur=cur->next,count++,p=p->next ){
if(count==m)
break;
}
if(!cur)
return NULL;
tear=cur;
next=cur->next;
for( ; cur ; cur=next , count++){
if(count>n)
break;
next=cur->next;
cur->next=p->next;
p->next=cur;
}
tear->next=next;
p=L->next;
delete L;
return p;
}
};