Value at index
Count hops from the head to reach the target position, guarding against short lists. About 8 minutes.
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.
curr starts at head (index 0, val 10). Hop 1 of 2.
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.
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 -1To reach index 3 in a list, how many times must you do curr = curr.next?
- A3 times
- B4 times
- C2 times
Show the answer
3 times. Starting at index 0: 1st hop lands on index 1, 2nd lands on index 2, 3rd lands on index 3.
Value at index
Given the head of a linked list and a 0-based integer index, return the value of the node at position index. If index is negative, or is greater than or equal to the number of nodes in the list, return -1.
head = [10, 20, 30, 40], index = 2 → 30
0 ≤ number of nodes ≤ 10,000 · -1,000,000 ≤ node.val ≤ 1,000,000 · -10,000 ≤ index ≤ 20,000