Find the middle node of a linked list
JavaScriptfunction middleNode(head) {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}Explanation
The fast pointer moves twice as fast as the slow pointer. When fast reaches the end, slow is automatically standing at the middle node.
Output
For 1 -> 2 -> 3 -> 4 -> 5, the function returns the node with value 3
Real-life Example
If one person walks one step and another walks two steps through the same queue, the slower person will be at the midpoint when the faster person reaches the end.