Given the head of a singly linked list, return the middle node. If there are two middle nodes, return the second one.
Move slow one step and fast two steps at a time. When fast runs off the end, slow is in the middle.
1function middleNode(head: ListNode | null): ListNode | null {2let slow = head, fast = head;3while (fast && fast.next) {4slow = slow!.next;5fast = fast.next.next;6}7return slow;8}
Both pointers start at the head.
Space: play/pause · ←/→: step