AlgoFrames

Length of a linked list

Warm-up · Write code · about 5 min

Given the head of a singly linked list, return how many nodes it has. An empty list (head is null) has length 0.

Example 1

Input:

[[4,8,15,16]]

Output:

4

Example 2

Input:

[[]]

Output:

0

No nodes at all.

Constraints

  • 0 ≤ number of nodes ≤ 5,000
  • -1,000 ≤ node value ≤ 1,000

Learn the idea first: Singly linked lists: traverse, insert, delete, a visual lesson.

More Singly linked lists: traverse, insert, delete problems