Write a function that counts the number of times a given int occurs in a Linked List | Java program to count occurrences in a linked list using recursion ; Represents node of a linkedlist ; 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 Code ; Start with the empty list ; Use push ( ) to construct below list 1 -> 2 -> 1 -> 3 -> 1 ; Check the count function
import java . io . * ; import java . util . * ; class Node { int data ; Node next ; Node ( int val ) { data = val ; next = null ; } } class GFG { static int frequency = 0 ; static Node push ( Node head , int new_data ) { Node new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; return head ; } static int count ( Node head , int key ) { if ( head == null ) return frequency ; if ( head . data == key ) frequency ++ ; return count ( head . next , key ) ; } public static void main ( String args [ ] ) { Node head = null ; head = push ( head , 1 ) ; head = push ( head , 3 ) ; head = push ( head , 1 ) ; head = push ( head , 2 ) ; head = push ( head , 1 ) ; System . out . print ( " count ▁ of ▁ 1 ▁ is ▁ " + count ( head , 1 ) ) ; } }