Middle of the linked list

problem [https://leetcode.com/problems/middle-of-the-linked-list/ 876. Middle of the Linked List].

Problem description
Given a non-empty, singly linked list with head node, return a middle node of linked list.

If there are two middle nodes, return the second middle node.


 * Example 1
 * Input: [1,2,3,4,5]
 * Output: Node 3 from this list (Serialization: [3,4,5]) The returned node has value 3. (The judge's serialization of this node is [3,4,5]). Note that we returned a   object , such that:.


 * Example 2
 * Input: [1,2,3,4,5,6]
 * Output: Node 4 from this list (Serialization: [4,5,6]) Since the list has two middle nodes with values 3 and 4, we return the second one.


 * Note
 * The number of nodes in the given list will be between  and.

Trivial cases

 * If the list is empty or only has one element, we just return the head directly.

General approach
We keep a slow pointer and a fast pointer.
 * In each iteration the fast pointer progresses by two steps, until hitting the end (becomes ).
 * In each iteration the slow pointer progresses by one step.


 * Special consideration : Odd vs. Even number of nodes
 * 1) Odd number of nodes Example: 1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
 * 2) * The fast pointer moves in this way: 1 → 3 → 5 → 7 → NULL (4 iterations)
 * 3) * The slow pointer moves in this way: 1 → 2 → 3 → 4 (3 iterations)
 * 4) Even number of nodes Example: 1 → 2 → 3 → 4 → 5 → 6 → NULL
 * 5) * The fast pointer moves in this way: 1 → 3 → 5 → NULL (3 iterations)
 * 6) * The slow pointer moves in this way: 1 → 2 → 3 → 4 (3 iterations)

We can see that:
 * 1) If the total number of nodes is odd, then the fast pointer goes over one more iteration than the slow pointer.
 * 2) If the total number of nodes is even, then the fast pointer goes over the same number of iterations than the slow pointer.

Time complexity
The time complexity is O(n), because we always have n/ 2 iterations to find the result, where n is the total number of nodes.

Space complexity

 * Stack
 * We only declared a slow pointer and a fast pointer. The space complexity on stack is O(1).


 * Heap
 * We did not allocate anything new on heap. The space complexity on heap is O(1).

So the total space complexity is O(1).

Variant: First middle node for even number of nodes
Sometimes we may need to return the first middle node if there are even number of nodes. For example:
 * Reorder list

In this case the approach is slightly different.

Example: 1 → 2 → 3 → 4 → 5 → 6 → NULL
 * The fast pointer moves in this way: 1 → 3 → 5 → NULL (3 iterations)
 * The slow pointer moves in this way: 1 → 2 → 3 (2 iterations)

Here we can see that the slow pointer has one less iteration than the fast iteration, similar to what we had in case of the total number of nodes is odd.