Moving forward k steps
To read the value at a given position, counting from 0, you need to advance across that many next pointers. Position 0 needs 0 hops, since it is the head itself. Position 1 needs 1 hop. In general, a loop running that many times takes you to the right node.
It is like walking down a corridor: to reach door 3 you pass three doors.
0 hops: the head is position 0.
k hops: leads to the node at position k.
Reach index 2 in list [10, 20, 30, 40]
10
020
130
240
3curr
curr starts at head (index 0, val 10). Hop 1 of 2.
Move 1 of 3
What if the list is too short?
If the position is 5 but the list only has 3 nodes, the pointer will become null before you finish taking your hops. Trying to read anything from a null pointer is a crash.
So check that the pointer is not null before each hop, and again before reading the value. A negative position is invalid too.
Null check: if the pointer is null at any point, the position is out of bounds.
Negative position: answer minus one immediately.
if index < 0:
return -1
curr = head
for _ in range(index):
if not curr:
return -1
curr = curr.next
return curr.val if curr else -1