Count of Prime Nodes of a Singly Linked List | Java 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
class solution { static class Node { int data ; Node next ; } static Node 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 ; return head_ref ; } static boolean 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 ; } static 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 ; } public static void main ( String args [ ] ) { Node head = null ; head = push ( head , 17 ) ; head = push ( head , 10 ) ; head = push ( head , 6 ) ; head = push ( head , 5 ) ; head = push ( head , 15 ) ; System . out . print ( " Count ▁ of ▁ prime ▁ nodes ▁ = ▁ " + countPrime ( head ) ) ; } }