# Reorder List

Problem:

Given a singly linked list L: L0 → L1 → ... → Ln-1 → Ln.

reorder it to: L0 → Ln → L1 → Ln-1 → ...

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 class Solution {
2 public:
4         // none or just one
6             return;
7
8         // more than one, adjust the first and the last
10         while(tail->next != NULL) {
11             pre = pre->next;
12             tail = tail->next;
13         }
14         pre->next = NULL;
17
18         // do it recursively
19         reorderList(tail->next);
20     }
21 };

 1 class Solution {
2 public:
4         // less than two elements
6             return;
7
8         // find the second half
9         ListNode *slow, *fast;
10         slow = fast = head;
11         while(fast->next != NULL && fast->next->next != NULL) {
12             slow = slow->next;
13             fast = fast->next;
14             fast = fast->next;
15         }
16
18         slow->next = NULL;
19
20         // reverse the second half
22         while(tail != NULL && tail->next != NULL) {
23             ListNode *cur = tail->next;
24             tail->next = cur->next;
27         }
28
29         // merge two parts
39 };