Write a function that counts the number of times a given int occurs in a Linked List

• Difficulty Level : Basic
• Last Updated : 13 Jan, 2022

Given a singly linked list and a key, count the number of occurrences of the given key in the linked list. For example, if the given linked list is 1->2->1->2->1->3->1 and the given key is 1, then the output should be 4.

Method 1- Without Recursion

Algorithm:

1. Initialize count as zero.
2. Loop through each element of linked list:
a) If element data is equal to the passed number then
increment the count.
3. Return count.

Implementation:

Javascript



Output:

count of 1 is 3

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 2- With Recursion
This method is contributed by MY_DOOM

Algorithm:

Algorithm
return frequency
increase frequency by 1

Implementation:

Javascript



Output:

count of 1 is 3

Below method can be used to avoid Global variable ‘frequency'(counter in case of Python 3 Code).

C++

 // method can be used to avoid // Global variable 'frequency'   /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ int count(struct Node* head, int key) {     if (head == NULL)         return 0;     if (head->data == key)         return 1 + count(head->next, key);     return count(head->next, key); }

Java

 // method can be used to avoid // Global variable 'frequency'   /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ int count(Node head, int key) {     if (head == null)         return 0;     if (head.data == key)         return 1 + count(head.next, key);     return count(head.next, key); }   // This code is contributed by rachana soma

C#

 // method can be used to avoid // Global variable 'frequency' using System;   /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ static int count(Node head, int key) {     if (head == null)         return 0;     if (head.data == key)         return 1 + count(head.next, key);     return count(head.next, key); }   // This code is contributed by SHUBHAMSINGH10

Python3

 def count(self, temp, key):           # during the initial call, temp     # has the value of head           # Base case     if temp is None:         return 0               # if a match is found, we     # increment the counter     if temp.data == key:         return 1 + count(temp.next, key)     return count(temp.next, key)       # to call count, use # linked_list_name.count(head, key)

Javascript



The above method implements head recursion. Below given is the tail recursive implementation for the same. Thanks to Puneet Jain for suggesting this approach :

int count(struct Node* head, int key)
{
return 0;

return 1 + frequency;

// else
return frequency;
}

Time Complexity: O(n)