问题描述如下:
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}
.
cpp代码如下:
class Solution {
public:
void reorderList(ListNode *head) {
if(head==NULL||head->next==NULL||head->next->next==NULL)return;
ListNode* f=head,*s=head;
while(true){
f=f->next;
if(!f)break;
f=f->next;
if(!f)break;
s=s->next;
}
f=s->next;
s->next=NULL;
s=NULL;
while(f->next){
ListNode* tmp=f->next;
f->next=s;
s=f;
f=tmp;
}
f->next=s;
for(s=head;f!=NULL;){
ListNode* tmp=f->next;
f->next=s->next;
s->next=f;
s=f->next;
f=tmp;
}
}
};