Find the Length of a Linked List

You are given the head pointer of a singly linked list. Count how many nodes the chain contains and return that number. An empty list (head is null) has…

You are given the head pointer of a singly linked list. Count how many nodes the chain contains and return that number. An empty list (`head` is null) has length 0. Examples serialize the node values from **head → tail**. For example, `head = [9, 2, 7, 4]` describes 9 → 2 → 7 → 4 → null, which has length 4.

- `0 <= n <= 10^5`, where `n` is the number of nodes - `-10^9 <= node.val <= 10^9` - The list is a proper singly linked list with no cycles.

Example 1: input head = [9,2,7,4]; output 4. Following next pointers visits 9, 2, 7, 4 before reaching null — four nodes.

Example 2: input head = [15]; output 1. A single node whose next pointer is null. The counter increments once.

Example 3: input head = []; output 0. The head is null, so the loop never runs and the count stays at 0.

Category: Linked List. Topic: linked-list. Difficulty: Easy. Patterns: linked-list-traversal.