用快慢指针将原链表分为两段,将fast指针那段倒置,一个一个插入前一段链表中。
有时间应去实现一下链表,另再看看别人的代码。
代码:
class Solution
{
public:
void reorderList(ListNode *head)
{
if (head == NULL || head->next==NULL)
{
return ;
}
// slow, towards, # = ceiling(n/2.0)
ListNode *fast= head, *slow=head;
for( ; fast->next!=NULL && fast->next->next!=NULL; slow = slow->next, fast = fast->next->next ) {}
fast = slow->next;
slow->next = NULL;
slow = head;
// fast, backwards, # = floor(n/2.0)
ListNode* prev = fast;
fast = fast->next;
prev->next = NULL;
while (fast != NULL)
{
ListNode* tmp = fast->next;
fast->next = prev;
prev = fast;
fast = tmp;
}
fast = prev;
for (ListNode* slow_next, *fast_next; fast != NULL; slow=slow_next, fast=fast_next)
{
slow_next = slow->next;
fast_next = fast->next;
slow->next = fast;
fast->next = slow_next;
}
}
};