Program to count the frequency of an element in linked list

Write a function that count the frequency or occurrence of a given element Or count the total number of nodes which have data equal to a given number.

C Program:

#include<stdio.h>
#include<stdlib.h>
 
struct Node{
    int data;
    struct Node *next;
};
 
/* Function to create new node */
struct Node *CreateNode(int n)
{
    struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data=n;
    newNode->next=NULL;
    return newNode;
}
 
void Push(struct Node **head,int n)
{
    struct Node *newNode = CreateNode(n);
    if(*head==NULL)
    {
        *head = newNode;
    }
    else
    {
        newNode->next = *head;
        *head = newNode;
    }
}
 
int CountFreq(struct Node *head,int num)
{
 /* Variable to count frequncy */
    int count = 0;
    struct Node *curr = head;
    while(curr!=NULL)
    {
    /* If data in node curr is equal to n 
    then increase count by one */
        if(num==curr->data)
        {
            count++;
        }
        curr = curr->next;
 
    }
    return count;
}
 
void PrintList(struct Node *head)
{
    struct Node *curr = head;
    if(curr==NULL)
    {
        printf("List is empty\n");
    }
    else{
    while(curr!=NULL)
    {
        printf("%d ",curr->data);
        curr= curr->next;
    }
    }
    printf("\n");
}
 
int main()
{
    struct Node *head=NULL;
    Push(&head,6);
    Push(&head,5);
    Push(&head,4);
    Push(&head,6);
    PrintList(head);
 
    int n;
    printf("Enter a number: ");
    scanf("%d",&n);
    int freq = CountFreq(head,n);
    printf("\nFrequency of %d is %d\n",n,freq);
 
    return 0;
}



Popular posts from this blog