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).
1 → 2 → 3 // → 3
7 // → 1
(empty) // → 0
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.
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.
next.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.
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.
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.
def list_length(head):
count = 0
node = head
while node is not None:
count += 1
node = node.next
return count
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.