Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find a node by value

Locate the first node that contains a given value and return its index.

Python practice8 minLinked ListsBeginnerLast updated March 27, 2026

Problem statement

Given the head of a singly linked list and an integer target value, return the index (0-based) of the first node whose value equals the target. If the target doesn't appear in the list, return -1. If the list is empty, return -1.

Task

Implement a function that returns the 0-based index of the first node containing the target value, or -1 if not found.

Examples

Find existing value

Input

head = build_linked_list([4, 5, 6]) find_node(head, 5)

Output

1

5 is at index 1 (0-based).

Input format

Two arguments: head (ListNode or None), value (int).

Output format

An integer index (0-based) or -1.

Constraints

- Node values and target are integers. - List length up to 10^5; run in O(n) time and O(1) extra space.

Samples

Sample 1

Input

build_linked_list([7,7,8]), 8

Output

2

The target 8 appears at index 2.