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:Â Â
Step 1: Start
Step 2: Create A Function Of A Linked List, Pass A Number
As Arguments And Provide The Count Of The Number To The Function.
Step 3: Initialize Count Equal To 0.
Step 4: Traverse In Linked List Until Equal Number Found.
Step 5: If Found A Number Equal To Update Count By 1.
Step 6: After Reaching The End Of The Linked List Return Count.
Step 7: Call The Function.
Step 8: Prints The Number Of Int Occurrences.
Step 9: Stop.
Implementation:Â Â
C++
// C++ program to count occurrences in a linked list#include <bits/stdc++.h>using namespace std;Â
/* Link list node */class Node {public:Â Â Â Â int data;Â Â Â Â Node* next;};Â
/* 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. */void push(Node** head_ref, int new_data){Â Â Â Â /* allocate node */Â Â Â Â Node* new_node = new Node();Â
    /* put in the data */    new_node->data = new_data;Â
    /* link the old list of the new node */    new_node->next = (*head_ref);Â
    /* move the head to point to the new node */    (*head_ref) = new_node;}Â
/* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/int count(Node* head, int search_for){Â Â Â Â Node* current = head;Â Â Â Â int count = 0;Â Â Â Â while (current != NULL) {Â Â Â Â Â Â Â Â if (current->data == search_for)Â Â Â Â Â Â Â Â Â Â Â Â count++;Â Â Â Â Â Â Â Â current = current->next;Â Â Â Â }Â Â Â Â return count;}Â
/* Driver program to test count function*/int main(){Â Â Â Â /* Start with the empty list */Â Â Â Â Node* head = NULL;Â
    /* Use push() to construct below list     1->2->1->3->1 */    push(&head, 1);    push(&head, 3);    push(&head, 1);    push(&head, 2);    push(&head, 1);Â
    /* Check the count function */    cout << "count of 1 is " << count(head, 1);    return 0;}Â
// This is code is contributed by rathbhupendra |
C
// C program to count occurrences in a linked list#include <stdio.h>#include <stdlib.h>Â
/* Link list node */struct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;};Â
/* 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. */void push(struct Node** head_ref, int new_data){    /* allocate node */    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));Â
    /* put in the data */    new_node->data = new_data;Â
    /* link the old list of the new node */    new_node->next = (*head_ref);Â
    /* move the head to point to the new node */    (*head_ref) = new_node;}Â
/* Counts the no. of occurrences of a node   (search_for) in a linked list (head)*/int count(struct Node* head, int search_for){    struct Node* current = head;    int count = 0;    while (current != NULL) {        if (current->data == search_for)            count++;        current = current->next;    }    return count;}Â
/* Driver program to test count function*/int main(){Â Â Â Â /* Start with the empty list */Â Â Â Â struct Node* head = NULL;Â
    /* Use push() to construct below list     1->2->1->3->1 */    push(&head, 1);    push(&head, 3);    push(&head, 1);    push(&head, 2);    push(&head, 1);Â
    /* Check the count function */    printf("count of 1 is %d", count(head, 1));    return 0;} |
Java
// Java program to count occurrences in a linked listimport java.io.*;class LinkedList {Â Â Â Â Node head; // head of listÂ
    /* Linked list Node*/    class Node {        int data;        Node next;        Node(int d)        {            data = d;            next = null;        }    }Â
    /* Inserts a new Node at front of the list. */    public void push(int new_data)    {        /* 1 & 2: Allocate the Node &                  Put in the data*/        Node new_node = new Node(new_data);Â
        /* 3. Make next of new Node as head */        new_node.next = head;Â
        /* 4. Move the head to point to new Node */        head = new_node;    }Â
    /* Counts the no. of occurrences of a node    (search_for) in a linked list (head)*/    int count(int search_for)    {        Node current = head;        int count = 0;        while (current != null) {            if (current.data == search_for)                count++;            current = current.next;        }        return count;    }Â
    /* Driver function to test the above methods */    public static void main(String args[])    {        LinkedList llist = new LinkedList();Â
        /* Use push() to construct below list          1->2->1->3->1 */        llist.push(1);        llist.push(2);        llist.push(1);        llist.push(3);        llist.push(1);Â
        /*Checking count function*/        System.out.println("Count of 1 is "                           + llist.count(1));    }}// This code is contributed by Rajat Mishra |
Python3
# Python program to count the number of time a given# int occurs in a linked listÂ
# Node class class Node:Â
    # Constructor to initialize the node object    def __init__(self, data):        self.data = data        self.next = NoneÂ
class LinkedList:Â
    # Function to initialize head    def __init__(self):        self.head = NoneÂ
    # Counts the no . of occurrences of a node    # (search_for) in a linked list (head)    def count(self, search_for):        current = self.head        count = 0        while(current is not None):            if current.data == search_for:                count += 1            current = current.next        return countÂ
    # Function to insert a new node at the beginning    def push(self, new_data):        new_node = Node(new_data)        new_node.next = self.head        self.head = new_nodeÂ
    # Utility function to print the LinkedList    def printList(self):        temp = self.head        while(temp):            print (temp.data)            temp = temp.nextÂ
Â
# Driver programllist = LinkedList()llist.push(1)llist.push(3)llist.push(1)llist.push(2)llist.push(1)Â
# Check for the count functionprint ("count of 1 is % d" %(llist.count(1)))Â
# This code is contributed by Nikhil Kumar Singh(nickzuck_007) |
C#
// C# program to count occurrences in a linked listusing System;class LinkedList {Â Â Â Â Node head; // head of listÂ
    /* Linked list Node*/    public class Node {        public int data;        public Node next;        public Node(int d)        {            data = d;            next = null;        }    }Â
    /* Inserts a new Node at front of the list. */    public void push(int new_data)    {        /* 1 & 2: Allocate the Node &                 Put in the data*/        Node new_node = new Node(new_data);Â
        /* 3. Make next of new Node as head */        new_node.next = head;Â
        /* 4. Move the head to point to new Node */        head = new_node;    }Â
    /* Counts the no. of occurrences of a node     (search_for) in a linked list (head)*/    int count(int search_for)    {        Node current = head;        int count = 0;        while (current != null) {            if (current.data == search_for)                count++;            current = current.next;        }        return count;    }Â
    /* Driver code */    public static void Main(String[] args)    {        LinkedList llist = new LinkedList();Â
        /* Use push() to construct below list         1->2->1->3->1 */        llist.push(1);        llist.push(2);        llist.push(1);        llist.push(3);        llist.push(1);Â
        /*Checking count function*/        Console.WriteLine("Count of 1 is " + llist.count(1));    }}Â
// This code is contributed by Arnab Kundu |
Javascript
<script>// javascript program to count occurrences in a linked listvar head; // head of listÂ
    /* Linked list Node */           class Node {            constructor(val) {                this.data = val;                this.next = null;            }        }Â
    /* Inserts a new Node at front of the list. */    function push(new_data) {        /*         * 1 & 2: Allocate the Node & Put in the data         */         new_node = new Node(new_data);Â
        /* 3. Make next of new Node as head */        new_node.next = head;Â
        /* 4. Move the head to point to new Node */        head = new_node;    }Â
    /*     * Counts the no. of occurrences of a node (search_for) in a linked list (head)     */    function count(search_for) {         current = head;        var count = 0;        while (current != null) {            if (current.data == search_for)                count++;            current = current.next;        }        return count;    }Â
    /* Driver function to test the above methods */              Â
        /*         * Use push() to construct below list 1->2->1->3->1         */        push(1);        push(2);        push(1);        push(3);        push(1);Â
        /* Checking count function */        document.write("Count of 1 is " + count(1));Â
// This code contributed by gauravrajput1 </script> |
count of 1 is 3
Time Complexity: O(n)Â
Auxiliary Space: O(1)
Method 2- With RecursionÂ
Algorithm:Â
Algorithm count(head, key); if head is NULL return frequency if(head->data==key) increase frequency by 1 count(head->next, key)
Implementation:Â Â
C++
// C++ program to count occurrences in a linked list using// recursion#include <bits/stdc++.h>using namespace std;Â
/* Link list node */struct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;};// global variable for counting frequency of// given element kint frequency = 0;Â
/* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the list. */void push(struct Node** head_ref, int new_data){    /* allocate node */    struct Node* new_node        = (struct Node*)malloc(sizeof(struct Node));Â
    /* put in the data */    new_node->data = new_data;Â
    /* link the old list of the new node */    new_node->next = (*head_ref);Â
    /* move the head to point to the new node */    (*head_ref) = new_node;}Â
/* 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 frequency;Â Â Â Â if (head->data == key)Â Â Â Â Â Â Â Â frequency++;Â Â Â Â return count(head->next, key);}Â
/* Driver program to test count function*/int main(){Â Â Â Â /* Start with the empty list */Â Â Â Â struct Node* head = NULL;Â
    /* Use push() to construct below list     1->2->1->3->1 */    push(&head, 1);    push(&head, 3);    push(&head, 1);    push(&head, 2);    push(&head, 1);Â
    /* Check the count function */    cout << "count of 1 is " << count(head, 1);    return 0;}Â
// This code is contributed by Aditya Kumar (adityakumar129) |
C
// C program to count occurrences in a linked list using// recursion#include <stdio.h>#include <stdlib.h>Â
/* Link list node */typedef struct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;} Node;// global variable for counting frequency of// given element kint frequency = 0;Â
/* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the list. */void push(Node** head_ref, int new_data){Â Â Â Â /* allocate node */Â Â Â Â Node* new_node = (Node*)malloc(sizeof(Node));Â
    /* put in the data */    new_node->data = new_data;Â
    /* link the old list of the new node */    new_node->next = (*head_ref);Â
    /* move the head to point to the new node */    (*head_ref) = new_node;}Â
/* 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 frequency;Â Â Â Â if (head->data == key)Â Â Â Â Â Â Â Â frequency++;Â Â Â Â return count(head->next, key);}Â
/* Driver program to test count function*/int main(){Â Â Â Â /* Start with the empty list */Â Â Â Â Node* head = NULL;Â
    /* Use push() to construct below list     1->2->1->3->1 */    push(&head, 1);    push(&head, 3);    push(&head, 1);    push(&head, 2);    push(&head, 1);Â
    /* Check the count function */    printf("count of 1 is %d", count(head, 1));    return 0;}Â
// This code is contributed by Aditya Kumar (adityakumar129) |
Java
// Java program to count occurrences in// a linked list using recursionimport java.io.*;import java.util.*;Â
// Represents node of a linkedlistclass Node {Â Â Â Â int data;Â Â Â Â Node next;Â Â Â Â Node(int val)Â Â Â Â {Â Â Â Â Â Â Â Â data = val;Â Â Â Â Â Â Â Â next = null;Â Â Â Â }}Â
class GFG {Â
    // global variable for counting frequency of    // given element k    static int frequency = 0;Â
    /* 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. */Â
    static Node push(Node head, int new_data)    {        // allocate node        Node new_node = new Node(new_data);Â
        // link the old list of the new node        new_node.next = head;Â
        // move the head to point to the new node        head = new_node;Â
        return head;    }Â
    /* 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 frequency;        if (head.data == key)            frequency++;        return count(head.next, key);    }Â
    // Driver Code    public static void main(String args[])    {        // Start with the empty list        Node head = null;Â
        /* Use push() to construct below list         1->2->1->3->1 */        head = push(head, 1);        head = push(head, 3);        head = push(head, 1);        head = push(head, 2);        head = push(head, 1);Â
        /* Check the count function */        System.out.print("count of 1 is " + count(head, 1));    }}Â
// This code is contributed by rachana soma |
Python3
# Python program to count the number of # time a given int occurs in a linked list# Node classclass Node:         # Constructor to initialize the node object    def __init__(self, data):        self.data = data        self.next = NoneÂ
class LinkedList:         # Function to initialize head    def __init__(self):        self.head = None        self.counter = 0             # Counts the no . of occurrences of a node    # (seach_for) in a linked list (head)    def count(self, li, key):                     # Base case         if(not li):             return self.counter                 # If key is present in         # current node, return true         if(li.data == key):             self.counter = self.counter + 1                 # Recur for remaining list         return self.count(li.next, key) Â
    # Function to insert a new node     # at the beginning    def push(self, new_data):        new_node = Node(new_data)        new_node.next = self.head        self.head = new_nodeÂ
    # Utility function to print the     # linked LinkedList    def printList(self):        temp = self.head        while(temp):            print (temp.data)            temp = temp.nextÂ
# Driver Codellist = LinkedList()llist.push(1)llist.push(3)llist.push(1)llist.push(2)llist.push(1)Â
# Check for the count functionprint ("count of 1 is", llist.count(llist.head, 1))Â
# This code is contributed by # Gaurav Kumar Raghav |
C#
// C# program to count occurrences in// a linked list using recursionusing System;Â
// Represents node of a linkedlistpublic class Node {Â Â Â Â public int data;Â Â Â Â public Node next;Â Â Â Â public Node(int val)Â Â Â Â {Â Â Â Â Â Â Â Â data = val;Â Â Â Â Â Â Â Â next = null;Â Â Â Â }}Â
class GFG {Â
    // global variable for counting frequency of    // given element k    static int frequency = 0;Â
    /* 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. */Â
    static Node push(Node head, int new_data)    {        // allocate node        Node new_node = new Node(new_data);Â
        // link the old list of the new node        new_node.next = head;Â
        // move the head to point to the new node        head = new_node;Â
        return head;    }Â
    /* 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 frequency;        if (head.data == key)            frequency++;        return count(head.next, key);    }Â
    // Driver Code    public static void Main(String[] args)    {        // Start with the empty list        Node head = null;Â
        /* Use push() to construct below list         1->2->1->3->1 */        head = push(head, 1);        head = push(head, 3);        head = push(head, 1);        head = push(head, 2);        head = push(head, 1);Â
        /* Check the count function */        Console.Write("count of 1 is " + count(head, 1));    }}Â
/* This code contributed by PrinciRaj1992 */ |
Javascript
<script>Â
// Javascript program to count occurrences in// a linked list using recursionÂ
// Represents node of a linkedlistclass Node {Â Â Â Â constructor(val)Â Â Â Â {Â Â Â Â Â Â Â Â this.data = val;Â Â Â Â Â Â Â Â this.next = null;Â Â Â Â }}Â
// Global variable for counting // frequency of given element klet frequency = 0;Â
/* Given a reference (pointer to pointer) to the head of a list and an int, push anew node on the front of the list. */function push(head, new_data){         // Allocate node    let new_node = new Node(new_data);Â
    // Link the old list of the new node    new_node.next = head;Â
    // Move the head to point to the new node    head = new_node;Â
    return head;}Â
/* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/function count(head, key){Â Â Â Â if (head == null)Â Â Â Â Â Â Â Â return frequency;Â Â Â Â if (head.data == key)Â Â Â Â Â Â Â Â frequency++;Â Â Â Â Â Â Â Â Â Â Â Â Â return count(head.next, key);}Â
// Driver codeÂ
// Start with the empty listlet head = null;Â
/* Use push() to construct below list      1->2->1->3->1 */head = push(head, 1);head = push(head, 3);head = push(head, 1);head = push(head, 2);head = push(head, 1);Â
/* Check the count function */document.write("count of 1 is " + Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â count(head, 1));Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â // This code is contributed by divyeshrabadiya07Â
</script> |
count of 1 is 3
Time complexity: O(n) where n is size of linked list
Auxiliary Space: O(n) for call stack since using recursionÂ
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)*/import java.io.*;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
<script>Â
// method can be used to afunction// Global variable 'frequency'Â
/* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/function count(head , 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 todaysgaurav Â
</script> |
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)
{
if(head == NULL)
return 0;
int frequency = count(head->next, key);
if(head->data == key)
return 1 + frequency;
// else
return frequency;
}
Time Complexity : O(n)Â
Auxiliary Space : O(n)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
