Middle of the Linked List

EasyFast and Slow Pointers

You are given the head of a non-empty singly linked list. Return its middle node.

When the list has an even number of nodes there are two middle nodes: return the second one.

Return the node itself, not its value. The tests read the list starting from the node you return, so the middle of 1 → 2 → 3 → 4 → 5 shows up as [3, 4, 5].

Constraints

  • The list has between 1 and 100 nodes.
  • -100 <= Node.val <= 100

Examples

Example 1

Input: head = [1,2,3,4,5]
Output: [3,4,5]

The middle of 5 nodes is the 3rd. The answer is that node, so the list from it onwards is 3 → 4 → 5.

Example 2

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]

With 6 nodes there are two middles, 3 and 4. Return the second one, 4.

Example 3

Input: head = [9]
Output: [9]

A single node is its own middle.

JavaScript you'll use: Linked list and tree nodes

/**
 * Linked list nodes are provided (you don't need to define them):
 * class ListNode { constructor(val = 0, next = null) { this.val = val; this.next = next; } }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
function middleNode(head) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.