原题
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}.
分析
比较简单的思路就是,按照原链表反着重新创建一个链表,然后69式,删去新链表里面多于的部分。
不过题目又说不让用多于的空间,只能“in place”,原地进行调整。
那就把链表拆开,分为两个链表,前半部分和后半部分。
1.前半部分不用修改。
2.后半部分做逆置操作。
3.69式插入
代码
class Solution
{
private:
void reverse(ListNode * &post)//逆置链表
{
if(post&&post->next)
{
ListNode *p1 = post;
ListNode *p2 = post->next;
ListNode *p3 = NULL;
while(p2!=NULL)
{
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
post->next=NULL;
post=p1;
}
else
{
return ;
}
}
public:
void reorderList(ListNode * head)
{
if(!head)
return ;
int count=0;
ListNode *p=head;
while(p!=NULL)
{
p=p->next;
count++;
}
count = (count+1)/2;//find pre
ListNode *pre=head;
ListNode *post=head;
int t=count;
while(--t)
{
post=post->next;
}
ListNode *r = post;
post=post->next;
r->next=NULL;
//cout << post->val<<endl;
// cout << count << endl;
reverse(post);
ListNode *pPre=pre;
ListNode *pPost=post;
ListNode *pNext=NULL;
while(pPost)
{
pNext=pPost->next;
pPost->next=pPre->next;
pPre->next=pPost;
pPre=pPost->next;
pPost=pNext;
}
head=pre;
}
};