Count of Prime Nodes of a Singly Linked List | C ++ implementation to find count of prime numbers in the singly linked list ; Node of the singly linked list ; Function to insert a node at the beginning of the singly Linked List ; Function to check if a number is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to find count of prime nodes in a linked list ; If current node is prime ; Update count ; Driver program ; start with the empty list ; create the linked list 15 -> 5 -> 6 -> 10 -> 17 ; Function call to print require answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } int countPrime ( Node * * head_ref ) { int count = 0 ; Node * ptr = * head_ref ; while ( ptr != NULL ) { if ( isPrime ( ptr -> data ) ) { count ++ ; } ptr = ptr -> next ; } return count ; } int main ( ) { Node * head = NULL ; push ( & head , 17 ) ; push ( & head , 10 ) ; push ( & head , 6 ) ; push ( & head , 5 ) ; push ( & head , 15 ) ; cout << " Count ▁ of ▁ prime ▁ nodes ▁ = ▁ " << countPrime ( & head ) ; return 0 ; }