← DiffPush

Count the number of nodes linked list

Baseline Linked List · Single Linked List O(N) · O(1)

Counting Wagons in the Marshalling Yard

Yard control receives a consist whose cars are chained one-way with no manifest attached, so the only way to size the train is to walk it: step from car to car, tally as you go, and stop when the coupling leads nowhere. The final tally is the train's length.

Input: An array arr representing the linked list's node values.

Output: The number of nodes in the list.

Constraints

Examples

Example 1

Input: {"arr":[1,2,3,4,5]}
Output: 5
The walk visits five cars before running off the end.

Example 2

Input: {"arr":[2,4,6,7,5,1,0]}
Output: 7
Seven nodes, so the tally stops at 7 — values play no role, only the count does.

Solve this in your browser →

Also on LeetCode ↗