Program:
#include<stdio.h>/*This structure is to represent the node of a single linked list */
struct node
{
int data;
struct node *next;
} *head,*temp,*temp1;
void create();
void print();
int counting(int);
void main()
{
int element,count;
create();
printf("\nElements in the entered list:\n");
print();
printf("\nEnter element:\n");
scanf("%d",&element);
count=counting(element);
printf("\nElement %d occured %d time(s) in the given Linked List\n",element,count);
}
/*Create function is for creating the linked list with the elements entered by the user. This is same as the create function in the previous programs on linked lists*/
void create()
{
int num;
printf("\nEnter element or enter -1 to exit\n");
head=(struct node*)malloc(sizeof(struct node));
scanf("%d",&num);
if(num==-1)
{
head=NULL;
}
else
{
head->data=num;
head->next=NULL;
}
while(head!=NULL)
{
printf("\nEnter element or enter -1 to exit\n");
scanf("%d",&num);
if(num==-1)
{break;}
else
{
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp1=(struct node*)malloc(sizeof(struct node));
temp1->data=num;
temp1->next=NULL;
temp->next=temp1;
}
}
}
/*counting function takes element as an argument and finds the number of occurrences of that element and returns the count value.This is the Main logic in this program*/
int counting(int element)
{
int count=0;
for(temp=head;temp!=NULL;temp=temp->next)
{
if(temp->data==element)
{
count++;
}
}
return count;
}
void print()
{
struct node *head1=head;
while(head1!=NULL)
{
printf("%d\t",head1->data);
head1=head1->next;
}
}
Output:
0 comments:
Post a Comment