Linked Lists Singly linked list basics
262. Length of a Linked List
You are given head, the first node of a singly linked list. Return the number of nodes in the list.
Each node holds a value and a pointer to the next node, and the last node's pointer is null. An empty list has no nodes, and its head is null. Its length is 0.
The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. Your
function gets only the head node, not this array.
Example 1
Input: head = [8, -3, 21, 0, 5]
5Explanation: The head holds 8. Its pointer leads to -3, then to 21, 0 and 5. The node holding 5 points to null, so the list has five nodes.
Example 2
Input: head = [0, -9, 0]
3Explanation: Two nodes hold 0. Each node counts once, whatever its value, so the length is 3.
Example 3
Input: head = []
0Explanation: The list is empty, so head is null and there are no nodes to count.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.