Count of Prime Nodes of a 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 ; Link list node ; Push a new node on the front of the list . ; Function to find count of prime nodes in a linked list ; If current node is prime ; Update count ; Driver Code ; Start with the empty list ; create the linked list 15 -> 5 -> 6 -> 10 -> 17 ; Function call to print require answer
def isPrime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return True NEW_LINE DEDENT if n % 2 == 0 or n % 3 == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if n % i == 0 or n % ( i + 2 ) == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return True NEW_LINE DEDENT class Node : NEW_LINE INDENT def __init__ ( self , data , next ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = next NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_node = Node ( new_data , self . head ) NEW_LINE self . head = new_node NEW_LINE DEDENT def countPrime ( self ) : NEW_LINE INDENT count = 0 NEW_LINE ptr = self . head NEW_LINE while ptr != None : NEW_LINE INDENT if isPrime ( ptr . data ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT ptr = ptr . next NEW_LINE DEDENT return count NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT linkedlist = LinkedList ( ) NEW_LINE linkedlist . push ( 17 ) NEW_LINE linkedlist . push ( 10 ) NEW_LINE linkedlist . push ( 6 ) NEW_LINE linkedlist . push ( 5 ) NEW_LINE linkedlist . push ( 15 ) NEW_LINE print ( " Count ▁ of ▁ prime ▁ nodes ▁ = " , linkedlist . countPrime ( ) ) NEW_LINE DEDENT