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}.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* split(ListNode *head)
{
if(head == NULL)
return NULL;
ListNode *a = head;
ListNode *b = head;
while (b->next && b->next->next)
{
a = a->next;
b = b->next;
b = b->next;
}
if(b->next)
{
a = a->next;
b = b->next;
}
ListNode *p = a->next;
a->next = NULL;
return p;
}
ListNode* reverse(ListNode *head)
{
if(head == NULL)
return NULL;
ListNode *p = head->next;
head->next = NULL;
while(p)
{
ListNode *q = p;
p = p->next;
q->next = head;
head = q;
}
return head;
}
void merge(ListNode *head1, ListNode *head2)
{
while(head2)
{
ListNode *p = head2;
head2 = head2->next;
p->next = head1->next;
head1->next = p;
head1 = head1->next;
head1 = head1->next;
}
}
void reorderList(ListNode* head)
{
if(head == NULL)
return;
ListNode *second = split(head);
second = reverse(second);
merge(head, second);
}
};