Title:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
struct ListNode
{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
void reorderList(ListNode *head)
{
ListNode *ptr;
ListNode *fast,*slow;
if(head==NULL||head->next==NULL||head->next->next==NULL)
return ;
fast=head;
slow=head;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
}
ListNode *preverse=slow;
if(slow==NULL)
return ;
ListNode *rehead=preverse->next;
preverse->next=NULL;
if(rehead==NULL)
return ;
ListNode *ptr1,*ptr2,*ptr3;
ptr1=rehead;
ptr2=rehead->next;
ptr3=rehead->next;
rehead->next=NULL;
while(ptr2!=NULL)
{
ptr3=ptr3->next;
ptr2->next=ptr1;
ptr1=ptr2;
ptr2=ptr3;
}
rehead=ptr1;
ptr=head;
while(ptr!=NULL&&rehead!=NULL)
{
ptr1=ptr->next;
ptr2=rehead->next;
ptr->next=rehead;
rehead->next=ptr1;
ptr=ptr1;
rehead=ptr2;
}
}