Write a C code to delete all prime numbers present in a doubly linked list. For example, if
input: 5->6->11->4->12->16, then output 6->4->12->16.
#include <stdio.h>
#include <stdbool.h>
struct doubleLinkedList {
int data;
struct doubleLinkedList *prev, *next;
};
void add(struct doubleLinkedList** head, int data)
{
struct doubleLinkedList* node = (struct doubleLinkedList*)malloc(sizeof(struct doubleLinkedList));
node->data = data;
node->prev = NULL;
node->next = (*head);
if ((*head) != NULL)
(*head)->prev =node;
(*head) = node;
}
bool isPrime(int x)
{
int i;
if (x <= 1)
return false;
if (x <= 3)
return true;
if (x % 2 == 0 || x % 3 == 0)
return false;
for (i = 5; i * i <= x; i = i + 6)
if (x % i == 0 || x % (i + 2) == 0)
return false;
return true;
}
void deleteItem(struct doubleLinkedList** head, struct doubleLinkedList* node)
{
if (*head == NULL || node == NULL)
return;
if (*head == node)
*head = node->next;
if (node->next != NULL)
node->next->prev = node->prev;
if (node->prev != NULL)
node->prev->next = node->next;
free(node);
return;
}
void deletePrimeNumbers(struct doubleLinkedList** head)
{
struct doubleLinkedList* ptr = *head;
struct doubleLinkedList* next;
while (ptr != NULL) {
next = ptr->next;
if (isPrime(ptr->data))
deleteItem(head, ptr);
ptr = next;
}
}
void display(struct doubleLinkedList* node)
{
while (node != NULL) {
printf("%d ", node->data );
node = node->next;
}
}
int main()
{
struct doubleLinkedList* node = NULL;
add(&node, 16);
add(&node, 12);
add(&node, 4);
add(&node, 11);
add(&node, 6);
add(&node, 5);
printf("Before modifying the List: \n");
display(node);
deletePrimeNumbers(&node);
printf("\nAfter modified the List:\n ");
display(node);
}
Comments
Leave a comment