Google Add

Search

Write a C Program to count the number of occurrences of an element in a single linked list


C Program to count the number of occurrences of an element in a single linked list


Logic

1. Traverse the linked list.

2. Increment the count when data passed is equal to traverse element .


// Program

#include<stdio.h>
#include<stdlib.h>

// Created node

struct node{

        int data;
        struct node* next;
};

void insertLinkedList(struct node** head,int value){

        struct node* temp = (struct node*) malloc(sizeof(struct node));

        temp->data = value;
        temp->next = (*head);
        (*head) = temp;

}

void countElement(struct node* head,int element){
    
        int count=0;

        while(head!=NULL){
                if(head->data == element){
                        count++;
                        head = head->next;
                }   
        }   

        printf("Count of an element is %d",count);

}


void main(){

        // Intialize the head node with NULL
                                                                                         struct node* head = NULL;

        insertLinkedList(&head,4);
        insertLinkedList(&head,6);
        insertLinkedList(&head,2);
        insertLinkedList(&head,4);

        // Printing the count of an element


        countElement(head,4);


}



No comments:

Post a Comment