Find the Length of a Linked List

Implement lengthOfLinkedList

Given the head of a singly linked list, return the number of nodes it contains. A linked list has no length field of its own — the only way to know how many nodes it has is to visit them. Both solutions do exactly that: the iterativeIterativeSolved with an explicit loop, keeping a running count in a local variable instead of the call stack. version keeps a running count in a local variable, while the recursiveRecursiveSolved by having the function call itself on a smaller version of the same problem — "the length of the rest of the list" is the same problem, just one node shorter — with each call contributing 1 for its own node. version builds the count as 1 + (length of everything after this node), accumulating the total as each call returns.

Example 1:

Input: head = [3,6,9,2,5]

Output: 5

Example 2:

Input: head = [7]

Output: 1

Example 3:

Input: head = []

Output: 0

+ 5 hidden test cases run on Submit.

Constraints:

  • 0 ≤ number of nodes in head ≤ 10⁴
  • -10⁹ ≤ node value ≤ 10⁹
  • An empty list has length 0

head =

[3, 6, 9, 2, 5]