DSA Factory
Free lessonsLinked lists · Stage 0 · Walking nodes · Step 1

Count the nodes

Walk from head to tail, counting each node until next is null. About 8 minutes.

The structure of a node

A linked list is made of nodes linked in a line. In code, every node has two fields: one holds the number, and the other points to the next node in line, or to nothing if it is the last one.

You are given the head, a pointer to the first node, and everything else you reach by following next pointers.

The value field: is the number stored inside the current node.
The next field: is the next node in the chain.
Walking a list [4, 7, 2], counting nodes
4
0
7
1
2
2
curr

curr = head (node 4). count = 1. curr = curr.next.

Move 1 of 4

Walking with a pointer

To visit every node, keep a pointer called curr, like a finger tracing a line of text. Start with the finger on the head. In a loop, do your work with the node under your finger, then move your finger to the next node.

Stop when the finger has gone past the last node and points at nothing.

Move to the next node: takes one step forward along the chain.
Loop while the pointer exists: it stops safely when you walk past the last node.
In code
count = 0
curr = head
while curr:
    count += 1
    curr = curr.next
return count
Quick check

A list has 3 nodes. How many times does curr = curr.next execute while counting them?

  1. A3 times
  2. B2 times
  3. C4 times
Show the answer

3 times. It moves from node 1 to 2, 2 to 3, and 3 to null (3 steps in total).

Your problem

Count the nodes

Given the head of a linked list, return the number of nodes in the list. If the list is empty (head is null), return 0.

Example
head = [4, 7, 2] → 3

0 ≤ number of nodes ≤ 10,000 · -1,000,000 ≤ node.val ≤ 1,000,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding