Reorder list

problem [https://leetcode.com/problems/reorder-list/ 143. Reorder List]

Problem description
Given a singly linked list L: $$L_0 \rightarrow L_1 \rightarrow L_2 \rightarrow \ldots \rightarrow L_n$$, reorder it to: $$L_0 \rightarrow L_n \rightarrow L_1 \rightarrow L_{n-1} \rightarrow L_2 \rightarrow L_{n-2} \rightarrow \ldots$$.

You may not modify the values in the list's nodes, only nodes itself may be changed.


 * Example 1
 * Given 1 → 2 → 3 → 4, reorder it to 1 → 4 → 2 → 3.


 * Example 2:
 * Given 1 → 2 → 3 → 4 → 5, reorder it to 1 → 5 → 2 → 4 → 3.

Analysis
We can break this problem into three subproblems:
 * 1) Find the Middle of the linked list, and break the linked list after the midpoint.
 * 2) * Note: In case of the number of nodes is even, we break after the first node of the middle.
 * 3) Reverse the second linked list.
 * 4) Alternatingly merge the two linked lists.

Time complexity

 * Finding the midpoint takes O(n/2) time complexity.
 * Reversing the second half takes O(n/2) time complexity.
 * Merging takes O(n/2) time complexity.
 * Add them up: the total time complexity = O(n/2) = O(n).

Auxiliary space complexity

 * Stack
 * 1) Finding midpoint: We used a slow and a fast pointer. The space complexity is O(1).
 * 2) Reversing the second half: We have kept a , a  , and a   pointer. The space complexity is O(1).
 * 3) Merging: We have kept a dummy head and the three pointers ,  , and  . The space complexity is O(1).

Total space complexity on stack is O(1).


 * Heap
 * We only have created the dummy node as the new object. So the total space complexity on heap is O(1).


 * Add them up: We see that the total auxiliary space complexity is O(1).