310. Count Occurrences of a Value in Linked List

EasyLinked ListLinked ListCountingTraversal

Given the head of a singly linked list and an integer target, return the number of nodes whose value equals target.

Traverse the entire list and count all matching nodes.

Input: Head of a singly linked list and integer target.

Output: Integer count of nodes with value equal to target.

Examples

Example 1
Input: [1,2,3,2,4,2,5], 2
Output: 3
Explanation: Value 2 appears at positions 2, 4, and 6. Count = 3.
Example 2
Input: [1,2,3,4,5], 6
Output: 0
Explanation: Value 6 not found in list. Count = 0.
Example 3
Input: [7,7,7,7,7], 7
Output: 5
Explanation: All 5 nodes have value 7. Count = 5.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →