Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.
void reorderList(ListNode *head) {
if (head == nullptr)
return;
//fast and low point to find the middle pos
ListNode* slow = head;
ListNode* fast = head;
if (fast->next == nullptr)
return;
fast = fast->next;
if (fast->next == nullptr)
return;
fast = fast->next;
while (fast->next != nullptr)
{
fast = fast->next;
if (fast->next != nullptr)
fast = fast->next;
slow = slow->next;
}
//split and reverse
ListNode* after = slow->next;
slow->next = nullptr;
ListNode* pre = nullptr;
while (after !=nullptr)
{
ListNode* temp = after->next;
if (temp == nullptr)
fast = after;
after->next = pre;
pre = after;
after = temp;
}
//merge fast and slow, slow is first
slow = head;
while (slow != nullptr && fast != nullptr)
{
pre = fast;
fast = fast->next;
pre->next = slow->next;
slow->next = pre;
slow = pre->next;
}
//only fast list can more than one
pre->next = fast;
}