题目描述:
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路:
1、先找到中间节点,然后翻转后半段,最后再插入到前半段
2、递归
3、使用容器存储
代码如下:
1、
class Solution {
public:
ListNode* reverse(ListNode *head){
ListNode *p1=NULL;
ListNode *p2=head;
ListNode *p3=head;
while(p2){
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
return p1;
}
void reorderList(ListNode* head) {
if(head==NULL||head->next==NULL) return;
ListNode* slow=head,*fast=head;
while(fast->next&&fast->next->next){//快慢指针找到中间结点
slow=slow->next;
fast=fast->next->next;
}
ListNode* needReverser=slow->next;//分成两段
slow->next=NULL;
needReverser=reverse(needReverser);//反转链表
ListNode *cur=head;
while(cur&&needReverser){//插入前端缝隙
ListNode *curSec=needReverser;
needReverser=needReverser->next;
ListNode *nextcur=cur->next;
curSec->next=cur->next;
cur->next=curSec;
cur=nextcur;
}
}
};
2、
class Solution {
public:
void reorderList(ListNode* head) {
if(!head||!head->next) return;
ListNode *p=head;
while(p->next->next){
p=p->next;
}
ListNode *inserP=p->next;
p->next=NULL;
inserP->next=head->next;
head->next=inserP;
reorderList(inserP->next);
}
};
3、
class Solution {
public:
void reorderList(ListNode* head) {
if(!head||!head->next) return;
vector<ListNode*>vec;
ListNode* p=head;
while(p){
vec.push_back(p);
p=p->next;
}
int left=0;
int right=vec.size()-1;
while(left<right){
vec[left]->next=vec[right];
vec[right]->next=vec[left+1];
right--;
left++;
}
vec[left]->next=NULL;
}
};