您的位置:首页 > 其它

leetcode143 Reorder List

2016-05-09 21:41 369 查看
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}
.

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
//分段
ListNode *p1,*p2;
p1=head;
p2=head;
if(!p2)
return;
p2=p2->next;

if(!p2)
return;

while(p1&&p1->next&&p2&&p2->next)
{
p1=p1->next;
p2=p2->next;
if(p2)
p2=p2->next;
}
if(p1)
{
p2=p1->next;
p1->next=NULL;
}
p1=head;

if(p1==p2)
return;

//反转
ListNode *tnode=p2;
p2=p2->next;
tnode->next=NULL;

while(p2)
{
ListNode *temp=p2;
p2=p2->next;
temp->next=tnode;
tnode=temp;
}

//连接
ListNode *t=tnode;

while(p1)
{

if(t)
{
ListNode *p12=p1;
p1=p1->next;
ListNode *t2=t;
t=t->next;
t2->next=p12->next;
p12->next=t2;
}
else
break;
}
}
};


note:反转时,42要放在43前面;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: