您的位置:首页 > 其它

leetcode-Reorder List

2014-07-11 19:32 330 查看
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}
.

思路:先利用快指针慢指针找到中间结点,将中间结点及其后面结点逆序,如{1,2,3,4}变成{1,2,4,3},然后再利用快指针慢指针将后面部分的结点一个一个插入。

代码:

 ListNode *reverseList(ListNode *head)

{
ListNode *curr=head;
ListNode *pre=head;
curr=curr->next;
while(curr!=NULL)
{
pre->next=curr->next;
curr->next=head;
head=curr;
curr=pre->next;
}
return head;

}

void reorderList(ListNode *head) 

{
if(head!=NULL && head->next!=NULL)
{
ListNode *slow=head;
ListNode *fast=head;
ListNode *pre=NULL;
while(fast!=NULL && fast->next!=NULL)
{
pre=slow;
slow=slow->next;
fast=fast->next->next;
}
pre->next=reverseList(slow);
slow=pre->next;
ListNode *fastCurr=slow;
ListNode *slowCurr=head;
ListNode *p=slowCurr;
ListNode *q=fastCurr;
while(fastCurr!=NULL && slowCurr!=slow)
{
p=slowCurr;
q=fastCurr;
slowCurr=slowCurr->next;
fastCurr=fastCurr->next;
p->next=q;
q->next=slowCurr;
}
q->next=fastCurr;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: