Here we are going to write a program to count the number of occurrence of given integer in a linked list using function. We will create a linked list and take a value from the user that he/she wants to count the occurrence of with the help of one counter variable and return the count.
Suppose we are given a linked list 1 => 2 => 3 => 4 => 3 => 2 => 1 => NULL and the given value to count its occurrence is 3, then our output should be 2.
Now lets implement it.
Program to Count the Number of occurrence of given integer in a Linked List using function -
C Code:
#include <stdio.h>
#include <malloc.h>
struct node{
int data;
struct node* next;
};
void create(struct node** head,int val){
struct node* ptr=*head;
struct node* new_node=(struct node*)malloc(sizeof(struct node));
new_node->data=val;
new_node->next=NULL;
if(*head==NULL){
*head=new_node;
return;
}
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=new_node;
}
void count(struct node* head,int val){
int c=0;
if(head==NULL){
printf("List is Empty!");
return;
}
struct node* ptr=head;
while(ptr->next!=NULL){
if (ptr->data==val){
c=c+1;
}
ptr=ptr->next;
}
printf("Occurrence of %d in the List : %d",val,c);
}
int main(){
struct node* head=NULL;
create(&head,1);
create(&head,2);
create(&head,2);
create(&head,4);
create(&head,3);
create(&head,5);
count(head,2);
return 0;
}Output -
Occurrence of 2 in the List : 2Time Complexity: O(n), where n = size of linked list
Linked List Problems-
Post a Comment
If you have any doubts, please let me know