Dhanashree Rugi

Posted on

# Occurrence of a Number in a Linked List.

Let us write a function that prints the number of times a number has occurred in a given linked list.

Example 1 :

Linked list : 2 6 4 4 5
Occurrence of number `4` : 2

Example 2 :

Linked list : 3 5 2 7 1 9
Occurrence of number `8` : 0

## Steps :

• Declare an integer variable `item` to store a number whose occurrence has to be found.

• Initialise an another integer variable `count` with `zero(0)` to store the number of times a number has occurred i.e., `count = 0`.

• Declare a temporary pointer `temp` of type `struct node` for traversing a linked list.

• Take the input(a number whose occurrence is to be found) from the user and initialise that user input to variable `item`.

• Start traversing a linked list until a number equal to `item` is found.

• If a number equal to the `item` is found , then update count by `1`.

• After reaching the end of linked list, print `count` and exit the function.

C program that finds the occurrence of number in a given linked list.

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

struct node
{
int data;
struct node * next;
};

{
int num = 0;
struct node * temp;
while(temp!=0)
{
printf("%d ",temp->data);
temp = temp->next;
num++;
}
}

{
int item, count = 0;
printf("\nEnter the number whose occurrence is to find : ");
scanf("%d", &item);

while(temp != NULL)
{
if(temp->data == item)
count++;
temp = temp->next;
}
printf("Occurrence of number  %d : %d", item, count);
}

int main()
{
struct node *head = 0, *newnode, *temp, *slow;
int n, choice, newdata;

printf("Enter the number of nodes in the list : ");
scanf("%d", &n);
for(int i = 1; i<=n; i++)
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data%d : ", i);
scanf("%d", &newnode->data);
newnode->next = 0;
{
}
else
{
temp->next = newnode;
temp = newnode;
}
}
printf("--------------------------------\n");