先将后len/2的链表节点翻转,再依次插入前半段链表中
class Solution {
public:
void reorderList(ListNode* head) {
if(head==NULL||head->next==NULL)
return;
int len=0;
ListNode* cur=head;
while(cur)
{
cur=cur->next;
len++;
}
if(len%2==0)
len/=2;
else
len=len/2+1;
cur=head;
for(int i=0;i<len-1;i++)
cur=cur->next;
ListNode* Head=cur->next,*pre=Head->next,*nx=NULL;
cur->next=NULL;
Head->next=NULL;
while(pre)
{
nx=pre->next;
pre->next=Head;
Head=pre;
pre=nx;
}
cur=head;
pre=Head;
while(pre)
{
nx=pre->next;
pre->next=cur->next;
cur->next=pre;
cur=pre->next;
pre=nx;
}
}
};应用快慢指针
class Solution {
public:
void reorderList(ListNode* head) {
if(head==NULL||head->next==NULL)
return;
ListNode* fast=head,*slow=head,*p=NULL,*q=NULL;
while(fast->next&&fast->next->next)
{
fast=fast->next->next;
slow=slow->next;
}
fast=slow->next;
slow->next=NULL;
p=fast,q=fast->next;
fast->next=NULL;
while(q)
{
ListNode* t=q->next;
q->next=p;
p=q;
q=t;
}
q=head;
while(p&&q)
{
ListNode* l=p->next,*r=q->next;
p->next=q->next;
q->next=p;
p=l;
q=r;
}
}
};
364

被折叠的 条评论
为什么被折叠?



