List Length

List Length

Return the number of nodes in a linked list.

listLength(head)

The node type is:

ListNode:
    value
    next   // reference to the next node, or nothing if this is the last one

Input format: space-separated node values (an empty line is the empty list).

Examples

1 → 2 → 3   // → 3
7           // → 1
(empty)     // → 0

Walkthrough

Thinking it through

A linked list doesn't give you random access or a built-in length like an array does — there's no way to ask "how big are you?" up front. Each node only knows its value and a pointer to the next one. So to count them, you have to actually visit each one.

Why traversal is unavoidable

Since each node only knows about the node after it, the only way to discover the list's extent is to start at the head and keep following next until you fall off the end. Nothing to sort or compare — just the simplest possible traversal, and nearly every other linked-list problem builds on this same loop shape.

Building the approach

  1. Start a counter at zero and a pointer at the head.
  2. While the pointer points to a real node, increment the counter and move the pointer to next.
  3. Once the pointer runs off the end, stop — the counter holds the total.

Handling the empty list for free

No special case needed: if the head is already the end-of-list marker, the loop body never runs, and the counter — still zero — is exactly right. This is a recurring theme in linked-list problems: "while there's a current node, do work, then advance" tends to make edge cases like an empty list resolve on their own.

Why this is efficient

Each node is visited once, so the work scales linearly — you can't do better, since you must touch every node to count them. And you only ever hold two things at a time: the counter and the current pointer, so the extra memory stays constant regardless of list length.

Where this pattern leads

Once "walk and accumulate" feels natural, you'll see it everywhere: summing values, collecting them into an array, searching for a target, checking a property across all nodes. Only the loop body changes — advancing a pointer until it runs out stays the same.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.