From : https://leetcode.com/problems/reorder-list/
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* reverse(ListNode* node) {
if(!node || !node->next) return node;
ListNode *p=node, *q=node->next, *t;
p->next = NULL;
while(q) {
t=q->next;
q->next=p;
p=q;
q=t;
}
return p;
}
void merge(ListNode* p, ListNode *q) {
ListNode *t;
while(q) {
t = q->next;
q->next = p->next;
p->next = q;
p = q->next;
q = t;
}
}
void reorderList(ListNode* head) {
if(!head || !head->next) return;
ListNode *fast=head, *slow=head;
//split
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
slow->next = NULL;
//reverse
fast = reverse(fast);
merge(head, fast);
}
};