Given a singly linked list l: l0→l1→ ... →ln-1→lN,
Reorder it to: l0→ln→l1→ln-1→l2→l N-2→ ...
You must does this in-place without altering the nodes ' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
classSolution { Public: voidReorderlist (ListNode *head) { if(!head| |!head->next)return; //partition the list into 2 sublists of equal lengthListNode *slownode = head, *fastnode =Head; while(fastnode->next) {Fastnode= fastnode->Next; if(fastnode->next) {Fastnode= fastnode->Next; } Else { Break; } Slownode= slownode->Next; } //2 sublist HeadsListNode *head1 = head, *head2 = slownode->Next; //Detach the sublistsSlownode->next =NULL; //reverse the second sublistListNode *cur = head2, *post = cur->Next; Cur->next =NULL; while(POST) {ListNode* Temp = post->Next; Post->next =cur; Cur=Post; Post=temp; } head2= cur;//The new head of the reversed sublist//Merge the 2 sublists as requiredlistnode* p = head1, *q =head2; while(q) {ListNode*TEMP1 = p->Next; ListNode*TEMP2 = q->Next; P->next =Q; Q->next =Temp1; P=Temp1; Q=Temp2; } } };
143. Reorder List (list)