Description: You are given a pointer to head node of a linked list. Your task is to find the number of times a number occurs in the given linked list.

 

If video does not load, Click here

Algorithm:

•       Initialize a count variable to 0

•       Loop through the linked list

–      If value of node is equal to given number, increment count

•       Return count

C Implementation

 
/* Link list node */
struct node
{
    int data;
    struct node* next;
};
 
/* Function to count the number of nodes*/
int count(struct node* head, int search_for)
{
    struct node* current = head;
/* Initialize a count variable to 0 */   
int count = 0;
/* Loop through the linked list
–      If value of node is equal to given number, increment count  */
     while(current != NULL)
    {
        if(current->data == search_for)
           count++;
        current = current->next;
    }
/* Return count */
    return count;
}

 

Time Complexity:

O(n)

Auxiliary Space:

O(1)

Go to top