Delete all Non-Prime Nodes from a Singly Linked List
Last Updated :
11 Jul, 2025
Given a singly linked list containing N nodes, the task is to delete all nodes from the list which are not prime.
Examples:
Input : List = 15 -> 16 -> 6 -> 7 -> 17
Output : Final List = 7 -> 17
Input : List = 15 -> 3 -> 4 -> 2 -> 9
Output : Final List = 3 ->2
Approach: The idea is to traverse the nodes of the singly linked list one by one and get the pointer of the nodes which are not prime. Delete those nodes by following the approach used in the post: Delete a node from Linked List.
Below is the implementation of above idea:
C++
// C++ implementation to delete all
// non-prime nodes from 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 delete all non-prime nodes
// from the singly linked list
void deleteNonPrimeNodes(Node** head_ref)
{
// Remove all composite nodes at the beginning
Node* ptr = *head_ref;
while (ptr != NULL && !isPrime(ptr->data)) {
Node* temp = ptr;
ptr = ptr->next;
delete (temp);
}
*head_ref = ptr;
if (ptr == NULL)
return;
// Remove remaining nodes
Node* curr = ptr->next;
while (curr != NULL) {
if (!isPrime(curr->data)) {
ptr->next = curr->next;
delete (curr);
curr = ptr->next;
}
else {
ptr = curr;
curr = curr->next;
}
}
}
// function to print nodes in a
// given singly linked list
void printList(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program
int main()
{
// start with the empty list
Node* head = NULL;
// create the linked list
// 15 -> 16 -> 7 -> 6 -> 17
push(&head, 17);
push(&head, 7);
push(&head, 6);
push(&head, 16);
push(&head, 15);
cout << "Original List: ";
printList(head);
deleteNonPrimeNodes(&head);
cout << "\nModified List: ";
printList(head);
}
Java
// Java implementation to delete all
// prime nodes from the singly
// linked list
import java.util.*;
// Node of the singly linked list
class Node {
int data;
Node next;
}
class GFG {
// function to insert a node at the beginning
// of the singly Linked List
static void push(Node head_ref[], int new_data)
{
// allocate node
Node new_node = new Node();
// put in the data
new_node.data = new_data;
// link the old list off the new node
new_node.next = head_ref[0];
// move the head to point to the new node
head_ref[0] = new_node;
}
// 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 delete a node in a singly Linked List.
// head_ref --> pointer to head node pointer.
// del --> pointer to node to be deleted
static void deleteNode(Node head_ref[], Node del)
{
// base case
if (head_ref[0] == null || del == null)
return;
// If node to be deleted is head node
if (head_ref[0] == del) {
head_ref[0] = del.next;
return;
}
// traverse list till not found
// delete node
Node temp = head_ref[0];
while (temp.next != del) {
temp = temp.next;
}
// copy address of node
temp.next = del.next;
// Finally, free the memory occupied by del
del = null;
}
// function to delete all prime nodes
// from the singly linked list
static void deletePrimeNodes(Node head_ref[])
{
Node ptr = head_ref[0];
Node next;
while (ptr != null) {
next = ptr.next;
// if true, delete node 'ptr'
if (isPrime(ptr.data) == false)
deleteNode(head_ref, ptr);
ptr = next;
}
}
// function to print nodes in a
// given singly linked list
static void printList(Node head)
{
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
}
// Driver Code
public static void main(String[] args)
{
// start with the empty list
Node[] head_ref = new Node[1];
head_ref[0] = null;
// create the linked list
// 15 -> 16 -> 7 -> 6 -> 17
push(head_ref, 17);
push(head_ref, 7);
push(head_ref, 6);
push(head_ref, 16);
push(head_ref, 15);
System.out.print("Original List: ");
printList(head_ref[0]);
deletePrimeNodes(head_ref);
System.out.print("\nModified List: ");
printList(head_ref[0]);
}
}
// this code is contributed by shubhamrajput6156
Python3
# Python3 implementation to delete all
# non-prime nodes from the singly
# linked list
import math
# Node of the singly linked list
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_ref, new_data):
new_node = Node(new_data)
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
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
for i in range(5, n + 1, 6):
if (i * i < n + 2 and
(n % i == 0 or n % (i + 2) == 0)):
return False
return True
# function to delete all non-prime nodes
# from the singly linked list
def deleteNonPrimeNodes(head_ref):
# Remove all composite nodes at the beginning
ptr = head_ref
while (ptr != None and
isPrime(ptr.data) != True):
temp = ptr
ptr = ptr.next
# delete(temp)
head_ref = ptr
if (ptr == None):
return None
# Remove remaining nodes
curr = ptr.next
while (curr != None):
if (isPrime(curr.data) != True):
ptr.next = curr.next
# delete(curr)
curr = ptr.next
else:
ptr = curr
curr = curr.next
return head_ref
# function to print nodes in a
# given singly linked list
def printList(head):
while (head != None):
print(head.data, end=" ")
head = head.next
# Driver Code
if __name__ == '__main__':
# start with the empty list
head = None
# create the linked list
# 15 -> 16 -> 7 -> 6 -> 17
head = push(head, 17)
head = push(head, 7)
head = push(head, 6)
head = push(head, 16)
head = push(head, 15)
print("Original List: ")
printList(head)
head = deleteNonPrimeNodes(head)
print("\nModified List: ")
printList(head)
# This code is contributed by AbhiThakur
C#
// C# implementation to delete all
// non-prime nodes from 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 delete all non-prime nodes
// from the singly linked list
static Node deleteNonPrimeNodes(Node head_ref)
{
// Remove all composite nodes
// at the beginning
Node ptr = head_ref;
while (ptr != null && !isPrime(ptr.data)) {
Node temp = ptr;
ptr = ptr.next;
}
head_ref = ptr;
if (ptr == null) {
return null;
}
// Remove remaining nodes
Node curr = ptr.next;
while (curr != null) {
if (!isPrime(curr.data)) {
ptr.next = curr.next;
curr = ptr.next;
}
else {
ptr = curr;
curr = curr.next;
}
}
return head_ref;
}
// function to print nodes in a
// given singly linked list
static void printList(Node head)
{
while (head != null) {
Console.Write(head.data + " ");
head = head.next;
}
}
// Driver code
public static void Main(String[] args)
{
// start with the empty list
Node head = null;
// create the linked list
// 15 . 16 . 7 . 6 . 17
head = push(head, 17);
head = push(head, 7);
head = push(head, 6);
head = push(head, 16);
head = push(head, 15);
Console.Write("Original List: ");
printList(head);
head = deleteNonPrimeNodes(head);
Console.Write("\nModified List: ");
printList(head);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// javascript implementation to delete all
// non-prime nodes from the singly
// linked list // Node of the singly linked list
class Node {
constructor() {
this.data = 0;
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 delete all non-prime nodes
// from the singly linked list
function deleteNonPrimeNodes(head_ref) {
// Remove all composite nodes at the beginning
var ptr = head_ref;
while (ptr != null && !isPrime(ptr.data)) {
var temp = ptr;
ptr = ptr.next;
}
head_ref = ptr;
if (ptr == null)
return null;
// Remove remaining nodes
var curr = ptr.next;
while (curr != null) {
if (!isPrime(curr.data)) {
ptr.next = curr.next;
curr = ptr.next;
} else {
ptr = curr;
curr = curr.next;
}
}
return head_ref;
}
// function to print nodes in a
// given singly linked list
function printList(head) {
while (head != null) {
document.write(head.data + " ");
head = head.next;
}
}
// Driver code
// start with the empty list
var head = null;
// create the linked list
// 15 . 16 . 7 . 6 . 17
head = push(head, 17);
head = push(head, 7);
head = push(head, 6);
head = push(head, 16);
head = push(head, 15);
document.write("Original List: ");
printList(head);
head = deleteNonPrimeNodes(head);
document.write("<br/>Modified List: ");
printList(head);
// This code contributed by aashish1995
</script>
OutputOriginal List: 15 16 6 7 17
Modified List: 7 17
Complexity Analysis:
- Time Complexity: O(N * sqrt(MAX) ) where N is the total number of nodes in the linked list and MAX is the maximum element in the array.
- Auxiliary Space: O(1).
Recursive Approach:
- Define a function called deleteNonPrimeNodesRecursive that takes a pointer to a node as its argument.
- If the given node is NULL (i.e., the end of the list has been reached), return NULL.
- Recursively call deleteNonPrimeNodesRecursive with the next node in the list as the argument.
- If the next node is NULL, return NULL.
- If the data in the next node is prime, return the next node.
- Otherwise, delete the next node, set the next pointer of the current node to the node after the deleted node, and recursively call deleteNonPrimeNodesRecursive with the current node as the argument.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Node of the singly linked list
struct Node {
int data;
Node* next;
};
// 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 delete all non-prime nodes recursively
Node* deleteNonPrimeNodes(Node* head)
{
if (head == NULL) {
return NULL;
}
if (isPrime(head->data)) {
head->next = deleteNonPrimeNodes(head->next);
return head;
}
return deleteNonPrimeNodes(head->next);
}
// function to print nodes in a given singly linked list
void printList(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->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;
}
// Driver program
int main()
{
// start with the empty list
Node* head = NULL;
// create the linked list
// 15 -> 16 -> 7 -> 6 -> 17
push(&head, 17);
push(&head, 6);
push(&head, 7);
push(&head, 16);
push(&head, 15);
cout << "Original List: ";
printList(head);
head = deleteNonPrimeNodes(head);
cout << "\nModified List: ";
printList(head);
return 0;
}
Java
class Node {
int data;
Node next;
}
public class DeleteNonPrimeNodes {
// Function to check if a number is prime
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;
}
// Function to delete all non-prime nodes recursively
static Node deleteNonPrimeNodes(Node head) {
if (head == null) {
return null;
}
if (isPrime(head.data)) {
head.next = deleteNonPrimeNodes(head.next);
return head;
}
return deleteNonPrimeNodes(head.next);
}
// Function to print nodes in a given singly linked list
static void printList(Node head) {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
}
// Function to insert a node at the beginning
// of the singly Linked List
static Node push(Node head, int new_data) {
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head;
head = new_node;
return head;
}
// Driver program
public static void main(String[] args) {
// start with the empty list
Node head = null;
// create the linked list
// 15 -> 16 -> 7 -> 6 -> 17
head = push(head, 17);
head = push(head, 6);
head = push(head, 7);
head = push(head, 16);
head = push(head, 15);
System.out.print("Original List: ");
printList(head);
head = deleteNonPrimeNodes(head);
System.out.print("\nModified List: ");
printList(head);
}
}
// This code is contributed by akshitaguprzj3
Python3
# Node of the singly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
# 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 delete all non-prime nodes recursively
def delete_non_prime_nodes(head):
if head is None:
return None
if is_prime(head.data):
head.next = delete_non_prime_nodes(head.next)
return head
return delete_non_prime_nodes(head.next)
# Function to print nodes in a given singly linked list
def print_list(head):
while head:
print(head.data, end=" ")
head = head.next
print()
# Function to insert a node at the beginning
# of the singly Linked List
def push(head_ref, new_data):
new_node = Node(new_data)
new_node.next = head_ref
head_ref = new_node
return head_ref
# Driver program
if __name__ == "__main__":
# start with the empty list
head = None
# create the linked list
# 15 -> 16 -> 7 -> 6 -> 17
head = push(head, 17)
head = push(head, 6)
head = push(head, 7)
head = push(head, 16)
head = push(head, 15)
print("Original List:", end=" ")
print_list(head)
head = delete_non_prime_nodes(head)
print("Modified List:", end=" ")
print_list(head)
C#
using System;
// node of the singly linked list
public class node {
public int data;
public node next;
}
public class linkedList {
// Function to check if a number is prime
public 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 delete all non-prime nodes recursively
public static node DeleteNonPrimeNodes(node head)
{
if (head == null) {
return null;
}
if (IsPrime(head.data)) {
head.next = DeleteNonPrimeNodes(head.next);
return head;
}
return DeleteNonPrimeNodes(head.next);
}
// Function to print nodes in a given
// singly linked list
public static void PrintList(node head)
{
while (head != null) {
Console.Write(head.data + " ");
head = head.next;
}
}
// Function to insert a node at the beginning
// of the singly Linked List
public static void Push(ref 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;
}
// Driver program
public static void Main()
{
// start with the empty list
node head = null;
// create the linked list
// 15 -> 16 -> 7 -> 6 -> 17
Push(ref head, 17);
Push(ref head, 6);
Push(ref head, 7);
Push(ref head, 16);
Push(ref head, 15);
Console.Write("Original List: ");
PrintList(head);
head = DeleteNonPrimeNodes(head);
Console.Write("\nModified List: ");
PrintList(head);
}
}
JavaScript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to check if a number is prime
function isPrime(n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 === 0 || n % 3 === 0) return false;
for (let i = 5; i * i <= n; i += 6) {
if (n % i === 0 || n % (i + 2) === 0) return false;
}
return true;
}
// Function to delete all non-prime nodes recursively
function deleteNonPrimeNodes(head) {
if (head === null) {
return null;
}
if (isPrime(head.data)) {
head.next = deleteNonPrimeNodes(head.next);
return head;
}
return deleteNonPrimeNodes(head.next);
}
// Function to print nodes in a given singly linked list
function printList(head) {
let current = head;
while (current !== null) {
console.log(current.data + " ");
current = current.next;
}
}
// 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;
}
// Driver program
let head = null;
// Create the linked list: 15 -> 16 -> 7 -> 6 -> 17
head = push(head, 17);
head = push(head, 6);
head = push(head, 7);
head = push(head, 16);
head = push(head, 15);
console.log("Original List: ");
printList(head);
head = deleteNonPrimeNodes(head);
console.log("\nModified List: ");
printList(head);
OutputOriginal List: 15 16 7 6 17
Modified List: 7 17
Time Complexity: O(n), where n is the length of the linked list.
Auxiliary Space: O(n), so the maximum depth of the recursive call stack is equal to the length of the linked list.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem