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.
curr = head (node 4). count = 1. curr = curr.next.
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.
count = 0
curr = head
while curr:
count += 1
curr = curr.next
return countA list has 3 nodes. How many times does curr = curr.next execute while counting them?
- A3 times
- B2 times
- 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).
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.
head = [4, 7, 2] → 3
0 ≤ number of nodes ≤ 10,000 · -1,000,000 ≤ node.val ≤ 1,000,000