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

Tracking your position

Nodes in a linked list do not know their own position. If you need to know which place a node occupies, you have to count for yourself, like counting the carriages on a train as you walk through it.

Start a counter at 0, and add 1 every time you step to the next node.

Counter starts at 0: it tracks how many hops you have made from the head.
Add one per step: it goes up with each step forward.
Search [5, 8, 3, 9] for target 3
5
0
8
1
3
2
9
3
curr

The pointer starts at the head (5), and the counter is 0. 5 is not 3. Advance.

Move 1 of 3

Returning early

When searching for the first occurrence of a value, check whether the current node holds the target. If it does, return the counter immediately and stop walking, because the problem asks for the first occurrence.

Only if the loop finishes without finding a match do you answer minus one.

Match found: return the counter right away.
Fall-through: the minus one belongs after the loop, not inside it.
In code
idx = 0
curr = head
while curr:
    if curr.val == target:
        return idx
    idx += 1
    curr = curr.next
return -1