# Delete all Prime Nodes from a Singly Linked List in C++

In this tutorial, we are going to learn how to delete all prime nodes from a singly linked list.

Let's see the steps to solve the problem.

• Write struct with data and next pointer.

• Write a function to insert the node into the singly linked list.

• Initialize the singly linked list with dummy data.

• Iterate over the singly linked list. Find whether the current node data is prime or not.

• If the current data is prime, then delete the node.

• Write a function to delete the node. Consider the following three cases while deleting the node.

• If the node is head node, then move the head to next node.

• If the node is middle node, then link the next node to the previous node

• If the node is end node, then remove the previous node link.

## Example

Let's see the code.

Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next;
};
void insertNode(Node** head_ref, int new_data) {
Node* new_node = (Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
}
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;
}
void deleteNode(Node** head_ref, Node* del) {
struct Node* temp = *head_ref;
if (*head_ref == NULL || del == NULL) {
return;
}
if (*head_ref == del) {
}
while (temp->next != del) {
temp = temp->next;
}
temp->next = del->next;
free(del);
return;
}
void deletePrimeNodes(Node** head_ref) {
Node* temp = *head_ref;
Node* next;
while (temp != NULL) {
next = temp->next;
if (isPrime(temp->data)) {
}
temp = next;
}
}
while (head != NULL) {
cout << head->data << " -> ";
}
}
int main() {
Node* head = NULL;
cout << "Linked List before deletion:" << endl;
cout << "\nLinked List after deletion:" << endl;
}

## Output

If you execute the above program, then you will get the following result.

Linked List before deletion:
6 -> 5 -> 4 -> 3 -> 2 -> 1 ->
Linked List after deletion:
6 -> 4 -> 1 ->

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 30-Dec-2020

336 Views

##### Kickstart Your Career

Get certified by completing the course