The challenge
Find the first node with a target value and return its zero-based index, or −1 if absent.
The input is an acyclic singly linked list.
Example
[4, 7, 2, 9], target 2 → index 2.
Use the walkthrough below to inspect the input and each state change.
See Traversal, step by step
Follow the pointers. Watch each link change.
A1Inspect node links
| Node | Value | Next |
|---|---|---|
| A1 | 4 | A2 |
| A2 | 7 | A3 |
| A3 | 2 | A4 |
| A4 | 9 | null |
Read the input
IDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links.
Start from the input head pointers.View original input
A: 4 (A1) → 7 (A2) → 2 (A3) → 9 (A4); parameters: {"target":2}
Parameter indices are zero-based, except n from the end, which is one-based. Node IDs remain fixed when links change.
Put it into code
Keep a current pointer and a position counter. Each next link advances by one.
Node stores val and next; the random-pointer lesson adds random. C++ uses C++17 or later.
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def search(head, target):
curr, index = head, 0
while curr:
if curr.val == target:
return index
curr = curr.next
index += 1
return -1
#include <cstddef>
struct Node {
int val;
Node* next;
Node(int value = 0, Node* link = nullptr)
: val(value), next(link) {}
};
int search(Node* head, int target) {
int index = 0;
while (head) {
if (head->val == target) return index;
head = head->next;
++index;
}
return -1;
}