[Naive Approach] By Recursion – O(n) time and O(n) space
The idea is to recursively traverse the linked list from the head. At each node, check if its value matches the given key; if it does, increment the count by 1. Then recursively call the function on the next node. When the pointer reaches NULL, return 0. The total count is obtained by summing the matches from all recursive calls.
Output
3
[Expected Approach] By Traversing each node – O(n) time and O(1) space
The idea is to traverse the linked list iteratively from the head, maintaining a counter. For each node, check if its value matches the key; if it does, increment the counter. Continue until the end of the list and return the final count.