# Count all Occurrences of node with particular value ‘x’ in a linked list

Count all Occurrences of node with particular value ‘x’ in a linked list” is a basic problem on linked list for beginners. Here, we are given a linked list and our task is to count all occurrences of nodes with given value ‘x’.

To do so, we need to traverse the complete linked list and increment the counter every time we encounter a node with value ‘x’.

Example:

```Suppose, we need to count the occurrence of the nodes with value ‘2’ in the following linked list.
Linked List: 1 -> 2 -> 3 -> 2 -> 2 -> 7 -> 2
The following list has 4 occurrences of Nodes with value as ‘2’.```

The steps to count all occurrences of nodes with given value are:

1. Initialize a counter with 0.
2. Traverse the complete linked list. While traversing, for every node, if the node value is ‘x’ or not. If the node value is ‘x’, then increment the counter.
3. Print the counter as the number of occurrences of the nodes with value ‘x’.

C++ Program to count all occurrences of nodes with given value is as follows:

```/* C++ Program to Count all Occurrences of particular node in a linked list */
#include<bits/stdc++.h>
using namespace std;
/* Structure of the node of the linked list */
struct node
{
int data;
struct node *next;
};

/* Function to Insert new node at the beginning of the linked list */
void insert_end(struct node **head, int ele)
{
/* Creating a new node */
struct node *new_node;
new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = ele;
new_node->next = NULL;

/* check whether the linked list is empty or not */

/* If the linked list is empty */
{
return;
}

/* if the linked list is not empty, then traverse the complete linked list and
points the pointer of the last node of the linked list to the new node */
struct node *temp = NULL;
while(temp->next != NULL)
temp=temp->next;
temp->next = new_node;
}

/* Function to count all Occurrences of particular node in a linked list */
{
/* Traverse the complete linked list and for every node encountered,
check whether node value is 'x' or not. If Node value is 'x', then increment
counter by 1. */
int counter = 0;
while(temp!=NULL)
{
if(temp->data == x)
counter++;
temp=temp->next;
}
return counter;
}

/* Function to print the linked list */
{
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
int main()
{
/* Insert Some Nodes of the Linked List */
cout<<"The elements of the linked list are:\n";
int x = 2;
```OUTPUT: