# Count nodes in a linked list with given value

Count nodes in a linked list with given value” is a basic programming problem based on linked list data structures for beginners. Here, we are given a linked list and our task is to count nodes in a linked list with given value.

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.
1 -> 2 -> 3 -> 2 -> 2 -> 7 -> 2
The following list has 4 occurrences of Nodes with value as ‘2’.```

The steps to count nodes in a linked list with given value are as follows:

1. Initialize a counter with 0.
2. Traverse the complete linked list. While traversing, for every node, check 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 nodes in a linked list with given value is as follows:

```/* C++ Program to Count nodes in a linked list with given value */
#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 */
int count(struct node *head,int x)
{
/* 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. */
struct node *temp = head;
int counter = 0;
while(temp!=NULL)
{
if(temp->data == x)
counter++;
temp=temp->next;
}
return counter;
}

/* Function to print the linked list */
void print(struct node *head)
{
struct node *p = head;
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;
int res = count(head,x);
cout<<"\nThe total number of nodes in a linked list with value as "<<x<<" is "<<res;
}
```
```OUTPUT:
The elements of the linked list are:
1 2 3 2 2 7 2
The total number of nodes in a linked list with value as 2 is 4```

Related Posts: