#include <bits/stdc++.h>
using
namespace
std;
struct
Node {
int
data;
struct
Node* next;
};
void
push(
struct
Node** head_ref,
int
data)
{
struct
Node* ptr1
= (
struct
Node*)
malloc
(
sizeof
(
struct
Node));
struct
Node* temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;
if
(*head_ref != NULL) {
while
(temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1;
*head_ref = ptr1;
}
void
deleteNode(Node* head_ref, Node* del)
{
struct
Node *temp = head_ref, *temp2 = head_ref;
while
(temp->next != del) {
temp = temp->next;
}
temp->next = del->next;
free
(del);
return
;
}
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
;
}
Node* deletePrimeNodes(Node* head)
{
if
(head == NULL)
return
NULL;
struct
Node* ptr = head;
struct
Node* temp;
while
(isPrime(ptr->data)) {
ptr = ptr->next;
if
(ptr == head) {
return
NULL;
}
}
temp = ptr;
Node* temp2 = ptr;
ptr = ptr->next;
while
(ptr != head) {
temp2 = ptr;
ptr = ptr->next;
}
temp2->next = temp;
head = temp;
ptr = head;
do
{
temp = ptr->next;
if
(isPrime(ptr->data))
deleteNode(head, ptr);
ptr = temp;
}
while
(ptr != head);
return
head;
}
void
printList(
struct
Node* head)
{
if
(!head) {
printf
(
"NULL"
);
}
struct
Node* temp = head;
if
(head != NULL) {
do
{
printf
(
"%d "
, temp->data);
temp = temp->next;
}
while
(temp != head);
}
}
int
main()
{
struct
Node* head = NULL;
push(&head, 20);
push(&head, 13);
push(&head, 6);
push(&head, 32);
push(&head, 11);
push(&head, 9);
cout <<
"Given List : "
;
printList(head);
cout <<
"\nList After deleting prime nodes : "
;
head = deletePrimeNodes(head);
printList(head);
return
0;
}