Write a function that counts the number of times a given int occurs in a Linked List | C ++ program to count occurrences in a linked list using recursion ; Link list node ; global variable for counting frequeancy of given element k ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; allocate node ; link the old list off the new node ; move the head to point to the new node ; Counts the no . of occurrences of a node ( search_for ) in a linked list ( head ) ; Driver program to test count function ; Start with the empty list ; Use push ( ) to construct below list 1 -> 2 -> 1 -> 3 -> 1 ; Check the count function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; int frequency = 0 ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int count ( struct Node * head , int key ) { if ( head == NULL ) return frequency ; if ( head -> data == key ) frequency ++ ; return count ( head -> next , key ) ; } int main ( ) { struct Node * head = NULL ; push ( & head , 1 ) ; push ( & head , 3 ) ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; cout << " count ▁ of ▁ 1 ▁ is ▁ " << count ( head , 1 ) ; return 0 ; }