Count of Prime Nodes of a Singly Linked List
Last Updated :
07 Dec, 2023
Given a singly linked list containing N nodes, the task is to find the total count of prime numbers.
Examples:
Input: List = 15 -> 5 -> 6 -> 10 -> 17
Output: 2
5 and 17 are the prime nodes
Input: List = 29 -> 3 -> 4 -> 2 -> 9
Output: 3
2, 3 and 29 are the prime nodes
Approach: The idea is to traverse the linked list to the end and check if the current node is prime or not. If YES, increment the count by 1 and keep doing the same until all the nodes get traversed.
Below is the implementation of above approach:
C++
// C++ implementation to find count of prime numbers
// in the singly linked list
#include <bits/stdc++.h>
using namespace std;
// Node of the singly linked list
struct Node {
int data;
Node* next;
};
// Function to insert a node at the beginning
// of the singly Linked List
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;
}
// Function to check if a number is prime
bool isPrime(int n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
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;
}
// Function to find count of prime
// nodes in a linked list
int countPrime(Node** head_ref)
{
int count = 0;
Node* ptr = *head_ref;
while (ptr != NULL) {
// If current node is prime
if (isPrime(ptr->data)) {
// Update count
count++;
}
ptr = ptr->next;
}
return count;
}
// Driver program
int main()
{
// start with the empty list
Node* head = NULL;
// create the linked list
// 15 -> 5 -> 6 -> 10 -> 17
push(&head, 17);
push(&head, 10);
push(&head, 6);
push(&head, 5);
push(&head, 15);
// Function call to print require answer
cout << "Count of prime nodes = "
<< countPrime(&head);
return 0;
}
Java
// Java implementation to find count of prime numbers
// in the singly linked list
class solution
{
// Node of the singly linked list
static class Node {
int data;
Node next;
}
// Function to insert a node at the beginning
// of the singly Linked List
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;
}
// Function to check if a number is prime
static boolean isPrime(int n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
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;
}
// Function to find count of prime
// nodes in a linked list
static int countPrime(Node head_ref)
{
int count = 0;
Node ptr = head_ref;
while (ptr != null) {
// If current node is prime
if (isPrime(ptr.data)) {
// Update count
count++;
}
ptr = ptr.next;
}
return count;
}
// Driver program
public static void main(String args[])
{
// start with the empty list
Node head = null;
// create the linked list
// 15 . 5 . 6 . 10 . 17
head=push(head, 17);
head=push(head, 10);
head=push(head, 6);
head=push(head, 5);
head=push(head, 15);
// Function call to print require answer
System.out.print( "Count of prime nodes = "+ countPrime(head));
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 implementation to find count of
# prime numbers in the singly linked list
# Function to check if a number is prime
def isPrime(n):
# Corner cases
if n <= 1:
return False
if n <= 3:
return True
# This is checked so that we can skip
# middle five numbers in below loop
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# Link list node
class Node:
def __init__(self, data, next):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
# Push a new node on the front of the list.
def push(self, new_data):
new_node = Node(new_data, self.head)
self.head = new_node
# Function to find count of prime
# nodes in a linked list
def countPrime(self):
count = 0
ptr = self.head
while ptr != None:
# If current node is prime
if isPrime(ptr.data):
# Update count
count += 1
ptr = ptr.next
return count
# Driver Code
if __name__ == "__main__":
# Start with the empty list
linkedlist = LinkedList()
# create the linked list
# 15 -> 5 -> 6 -> 10 -> 17
linkedlist.push(17)
linkedlist.push(10)
linkedlist.push(6)
linkedlist.push(5)
linkedlist.push(15)
# Function call to print require answer
print("Count of prime nodes =",
linkedlist.countPrime())
# This code is contributed by Rituraj Jain
C#
// C# implementation to find count of prime numbers
// in the singly linked list
using System;
class GFG
{
// Node of the singly linked list
public class Node
{
public int data;
public Node next;
}
// Function to insert a node at the beginning
// of the singly Linked List
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;
}
// Function to check if a number is prime
static bool isPrime(int n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
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;
}
// Function to find count of prime
// nodes in a linked list
static int countPrime(Node head_ref)
{
int count = 0;
Node ptr = head_ref;
while (ptr != null)
{
// If current node is prime
if (isPrime(ptr.data))
{
// Update count
count++;
}
ptr = ptr.next;
}
return count;
}
// Driver code
public static void Main(String []args)
{
// start with the empty list
Node head = null;
// create the linked list
// 15 . 5 . 6 . 10 . 17
head=push(head, 17);
head=push(head, 10);
head=push(head, 6);
head=push(head, 5);
head=push(head, 15);
// Function call to print require answer
Console.Write( "Count of prime nodes = "+ countPrime(head));
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// Javascript implementation to find count
// of prime numbers in the singly linked list
// Node of the singly linked list
class Node
{
constructor(val)
{
this.data = val;
this.next = null;
}
}
// Function to insert a node at the beginning
// of the singly Linked List
function push(head_ref, new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
// Function to check if a number is prime
function isPrime(n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for(i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
// Function to find count of prime
// nodes in a linked list
function countPrime(head_ref)
{
var count = 0;
var ptr = head_ref;
while (ptr != null)
{
// If current node is prime
if (isPrime(ptr.data))
{
// Update count
count++;
}
ptr = ptr.next;
}
return count;
}
// Driver code
// Start with the empty list
var head = null;
// Create the linked list
// 15 . 5 . 6 . 10 . 17
head = push(head, 17);
head = push(head, 10);
head = push(head, 6);
head = push(head, 5);
head = push(head, 15);
// Function call to print require answer
document.write("Count of prime nodes = " +
countPrime(head));
// This code is contributed by gauravrajput1
</script>
OutputCount of prime nodes = 2
Complexity Analysis:
- Time Complexity: O(N*sqrt(P)), where N is length of the LinkedList and P is the maximum element in the List
- Auxiliary Space: O(1)
Recursive Approach:
The base case of the recursion is when the head node is NULL, in which case the function returns 0. Otherwise, the function first calls itself recursively for the next node in the linked list, and obtains the count of prime nodes in the remaining linked list. If the data of the current node is prime, it adds 1 to the count and returns it, otherwise it simply returns the count obtained from the recursive call. The final result returned by the function is the count of prime nodes in the entire linked list.
- If the head node is NULL, return 0.
- Recursively call the function for the rest of the linked list by passing the next node.
- If the data of the current node is prime, add 1 to the count and return it.
- Otherwise, return the count obtained from the recursive call.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
// Node of the singly linked list
struct Node {
int data;
Node* next;
};
// Function to insert a node at the beginning
// of the singly linked list
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;
}
// Function to check if a number is prime
bool isPrime(int n) {
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
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;
}
// Function to count prime nodes in a linked list
int countPrimeRecursive(Node* head) {
if (head == NULL)
return 0;
int count = countPrimeRecursive(head->next);
if (isPrime(head->data))
count++;
return count;
}
// Driver program
int main() {
// start with the empty list
Node* head = NULL;
// create the linked list
// 15 -> 5 -> 6 -> 10 -> 17
push(&head, 17);
push(&head, 10);
push(&head, 6);
push(&head, 5);
push(&head, 15);
// Function call to print required answer
cout << "Count of prime nodes = " << countPrimeRecursive(head);
return 0;
}
Java
// Java program of the above approach
class Node {
int data;
Node next;
Node(int data)
{
this.data = data;
this.next = null;
}
}
public class GFG {
// Function to insert a node at the beginning
// of the singly linked list
static Node push(Node head, int newData)
{
Node newNode = new Node(newData);
newNode.next = head;
return newNode;
}
// Function to check if a number is prime
static boolean isPrime(int n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
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;
}
// Function to count prime nodes in a linked list
static int countPrimeRecursive(Node head)
{
if (head == null)
return 0;
int count = countPrimeRecursive(head.next);
if (isPrime(head.data))
count++;
return count;
}
// Driver program
public static void main(String[] args)
{
// Start with an empty list
Node head = null;
// Create the linked list
// 15 -> 5 -> 6 -> 10 -> 17
head = push(head, 17);
head = push(head, 10);
head = push(head, 6);
head = push(head, 5);
head = push(head, 15);
// Function call to print the required answer
System.out.println("Count of prime nodes = "
+ countPrimeRecursive(head));
}
}
// This code is contributed by Susobhan Akhuli
Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to insert a node at the beginning
# of the singly linked list
def push(head, new_data):
new_node = Node(new_data)
new_node.next = head
return new_node
# Function to check if a number is prime
def is_prime(n):
# Corner cases
if n <= 1:
return False
if n <= 3:
return True
# This is checked so that we can skip
# middle five numbers in below loop
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# Function to count prime nodes in a linked list
def count_prime_recursive(head):
if head is None:
return 0
count = count_prime_recursive(head.next)
if is_prime(head.data):
count += 1
return count
# Driver program
if __name__ == "__main__":
# Start with an empty list
head = None
# Create the linked list
# 15 -> 5 -> 6 -> 10 -> 17
head = push(head, 17)
head = push(head, 10)
head = push(head, 6)
head = push(head, 5)
head = push(head, 15)
# Function call to print the required answer
print("Count of prime nodes =", count_prime_recursive(head))
C#
using System;
// Node of the singly linked list
class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
public class GFG
{
// Function to insert a node at the beginning of the singly linked list
static Node Push(Node head, int newData)
{
Node newNode = new Node(newData);
newNode.next = head;
return newNode;
}
// Function to check if a number is prime
static bool IsPrime(int n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in the loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i += 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
// Function to count prime nodes in a linked list
static int CountPrimeRecursive(Node head)
{
if (head == null)
return 0;
int count = CountPrimeRecursive(head.next);
if (IsPrime(head.data))
count++;
return count;
}
// Driver program
public static void Main(string[] args)
{
// Start with an empty list
Node head = null;
// Create the linked list: 15 -> 5 -> 6 -> 10 -> 17
head = Push(head, 17);
head = Push(head, 10);
head = Push(head, 6);
head = Push(head, 5);
head = Push(head, 15);
// Function call to count prime nodes and print the result
Console.WriteLine("Count of prime nodes = " + CountPrimeRecursive(head));
}
}
JavaScript
// Node of the singly linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to insert a node at the beginning
// of the singly linked list
function push(head, new_data) {
let new_node = new Node(new_data);
new_node.next = head;
head = new_node;
return head;
}
// Function to check if a number is prime
function isPrime(n) {
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 === 0 || n % 3 === 0)
return false;
for (let i = 5; i * i <= n; i = i + 6)
if (n % i === 0 || n % (i + 2) === 0)
return false;
return true;
}
// Function to count prime nodes in a linked list
function countPrimeRecursive(head) {
if (head === null)
return 0;
let count = countPrimeRecursive(head.next);
if (isPrime(head.data))
count++;
return count;
}
// Driver program
let head = null;
// Create the linked list: 15 -> 5 -> 6 -> 10 -> 17
head = push(head, 17);
head = push(head, 10);
head = push(head, 6);
head = push(head, 5);
head = push(head, 15);
// Function call to print the required answer
console.log("Count of prime nodes =", countPrimeRecursive(head));
OutputCount of prime nodes = 2
Time Complexity: O(N), where N is the number of nodes in the linked list.
Space Complexity: O(N), where N is the number of nodes in the linked list. This is because we create a recursive call stack for each node.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read