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

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. 

Python Programming:

[pastacode lang=”python” manual=”%23%20Python%20program%20to%20count%20the%20number%20of%20time%20a%20given%0A%23%20int%20occurs%20in%20a%20linked%20list%0A%20%0A%23%20Node%20class%20%0Aclass%20Node%3A%0A%20%0A%20%20%20%20%23%20Constructor%20to%20initialize%20the%20node%20object%0A%20%20%20%20def%20__init__(self%2C%20data)%3A%0A%20%20%20%20%20%20%20%20self.data%20%3D%20data%0A%20%20%20%20%20%20%20%20self.next%20%3D%20None%0A%20%0Aclass%20LinkedList%3A%0A%20%0A%20%20%20%20%23%20Function%20to%20initialize%20head%0A%20%20%20%20def%20__init__(self)%3A%0A%20%20%20%20%20%20%20%20self.head%20%3D%20None%0A%20%0A%20%20%20%20%23%20Counts%20the%20no%20.%20of%20occurances%20of%20a%20node%0A%20%20%20%20%23%20(seach_for)%20in%20a%20linkded%20list%20(head)%0A%20%20%20%20def%20count(self%2C%20search_for)%3A%0A%20%20%20%20%20%20%20%20current%20%3D%20self.head%0A%20%20%20%20%20%20%20%20count%20%3D%200%0A%20%20%20%20%20%20%20%20while(current%20is%20not%20None)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20current.data%20%3D%3D%20search_for%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20count%20%2B%3D%201%0A%20%20%20%20%20%20%20%20%20%20%20%20current%20%3D%20current.next%0A%20%20%20%20%20%20%20%20return%20count%0A%20%0A%20%20%20%20%23%20Function%20to%20insert%20a%20new%20node%20at%20the%20beginning%0A%20%20%20%20def%20push(self%2C%20new_data)%3A%0A%20%20%20%20%20%20%20%20new_node%20%3D%20Node(new_data)%0A%20%20%20%20%20%20%20%20new_node.next%20%3D%20self.head%0A%20%20%20%20%20%20%20%20self.head%20%3D%20new_node%0A%20%0A%20%20%20%20%23%20Utility%20function%20to%20print%20the%20linked%20LinkedList%0A%20%20%20%20def%20printList(self)%3A%0A%20%20%20%20%20%20%20%20temp%20%3D%20self.head%0A%20%20%20%20%20%20%20%20while(temp)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print%20temp.data%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20temp%20%3D%20temp.next%0A%20%0A%20%0A%23%20Driver%20program%0Allist%20%3D%20LinkedList()%0Allist.push(1)%0Allist.push(3)%0Allist.push(1)%0Allist.push(2)%0Allist.push(1)%0A%20%0A%23%20Check%20for%20the%20count%20function%0Aprint%20%22count%20of%201%20is%20%25d%22%20%25(llist.count(1))%0A%20%0A%23%20This%20code%20is%20contributed%20by%20Nikhil%20Kumar%20Singh(nickzuck_007)%0A” message=”” highlight=”” provider=”manual”/]

Output:

count of 1 is 3

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

[ad type=”banner”]