ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode dummy(0), *ins = &dummy;
dummy.next = head;
for (int i = 0; i < m-1; ++i)
ins = ins->next;
ListNode *cur = ins->next;
for (int i = 0; i < n-m; ++i) {
ListNode *move = cur->next;
cur->next = move->next;
move->next = ins->next;
ins->next = move;
}
return dummy.next;
}
//another flavor
ListNode *reverseBetween(ListNode *head, int m, int n) {
int c=n-m;
if(c==0) return head;
ListNode*dhead,*dtail;
dhead=dtail=head;
ListNode dummy(0);dummy.next=head;
ListNode*prev=&dummy;
while(c>0){
dtail=dtail->next;c--;
}
while(--m>0)
{
prev=dhead;
dhead=dhead->next;
dtail=dtail->next;
}
ListNode*end=dtail->next;
ListNode*curr=dhead;
while(curr->next!=end)
{
ListNode*ne=curr->next->next;
curr->next->next=prev->next;
prev->next=curr->next;
curr->next=ne;
}
return dummy.next;
}
No comments:
Post a Comment