Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

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