Fundamentals/Linked List vs Array
← PrevNext →
Implement indexOfValue(head, target) that searches a singly linked list for the first node whose value equals target, and returns its 0-based index in the list. If no node matches, return -1.
Walk the list from head, comparing each node's value (val field) to target with strict equality. Count nodes as you traverse so the first node is index 0, the second is index 1, and so on. An empty list (head is null) always returns -1.
Input
head: the head node of a singly linked list (may be null)
target: the value to search for
Output
The 0-based index of the first node whose value equals target, or -1 if no such node exists.
Examples
Example 1
Inputhead = 1 -> 2 -> 3 -> null, target = "hello"
Output-1
Explanation: None of the nodes hold the value "hello", so the search returns -1.
Example 2
Inputhead = 1 -> null, target = "abcde"
Output-1
Example 3
Inputhead = null, target = "a"
Output-1
Explanation: An empty list has no nodes to match, so the result is -1.
Constraints
Use strict equality when comparing node values to target.
Run in O(n) time where n is the number of nodes in the list.