Problem 245196 · easy · Phase 02 Linear Data Structures

Count the Nodes

linked list · traversal

Given the head of a singly linked list, return the number of nodes it contains.

Examples

Input:  head = 4 -> 7 -> 1
Output: 3

Input:  head = (empty)
Output: 0

Constraints

  • 0 <= number of nodes <= 10**4
  • Target: O(n) time, O(1) extra space

Goals

  • Walk a linked list with a while loop until the pointer becomes None
  • Handle the empty list, where head itself is None
Starting Python…