DEV Community

Cover image for Occurrence of a Number in a Linked List.
Dhanashree Rugi
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;
};  

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

void occurrence(struct node *head)
{
   struct node *temp = head;
   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;

// Create Linked List //

   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;
   if(head == 0)
    {
        head = temp = newnode;
    } 
    else
       { 
        temp->next = newnode;
        temp = newnode;
       }
 }
   printf("--------------------------------\n");
   printf("Linked list : ");
   displayLL(head);
   occurrence(head);
}
Enter fullscreen mode Exit fullscreen mode

I own a website www.coderlogs.com where in I write similar blogs so do visit the website for more such blog posts.

Top comments (0)