问题描述: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)将反转后的链表插入第一个链表中
代码的实现如下:
/**
* 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)
{
if(head==NULL || head->next==NULL || head->next->next==NULL)
return;
//第一步:将链表从中间分开变成两个链表
ListNode* fast=head;
ListNode* slow=head;
while(fast->next!=NULL && fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
}
ListNode* mid=slow->next;
slow->next=NULL;
//第二步:将拆好的第二部分的链表翻转
ListNode* last=mid;
ListNode* prev=NULL;
while(last!=NULL)
{
ListNode* next = last->next;
last->next=prev;
prev=last;
last=next;
}
//第三步:将翻转后的链表插入第一个链表中
while(head!=NULL && prev!=NULL)
{
ListNode* next = head->next;
head->next=prev;
prev=prev->next;
head->next->next=next;
head=next;
}
}
};