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}变成{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;
}
}
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;
}
}
相关文章推荐
- [leetcode] Reorder List
- *LeetCode-Reorder List
- [LeetCode] Reorder List
- leetcode--Reorder List
- leetcode--Reorder List
- Reorder List - Leetcode
- LeetCode-Reorder List
- [leetcode]Reorder List
- 《leetCode》:Reorder List
- LeetCode143 Reorder List
- LeetCode - Reorder List
- leetcode143~Reorder List
- ]Leetcode]-[Reorder List ]-三种解法
- [LeetCode 143] Reorder List Solution
- LeetCode解题报告:Reorder List
- [LeetCode] 重排链表 reorder linked list
- LeetCode - Reorder List
- Leetcode -- Reorder List
- Leetcode--Reorder List
- [LeetCode]Reorder List