# Delete all the nodes from a doubly linked list that are smaller than a given value in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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

Let's see the steps to solve the problem.

• Write struct with data, prev and next pointers.

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

• Initialize the doubly linked list with dummy data.

• Iterate over the doubly linked list. Find whether the current node data is less than given value or not.

• If the current data is less than the given value, 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 *prev, *next;
};
void insertNode(Node** head_ref, int new_data) {
Node* new_node = (Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = NULL;
if ((*head_ref) != NULL) {
}
}
void deleteNode(Node** head_ref, Node* del) {
if (*head_ref == NULL || del == NULL) {
return;
}
if (*head_ref == del) {
}
if (del->next != NULL) {
del->next->prev = del->prev;
}
if (del->prev != NULL) {
del->prev->next = del->next;
}
free(del);
return;
}
void deleteSmallerNodes(Node** head_ref, int K) {
Node* temp = *head_ref;
Node* next;
while (temp != NULL) {
next = temp->next;
if (temp->data < K) {
}
temp = next;
}
}
while (head != NULL) {
cout << head->data << " -> ";
}
}
int main() {
Node* head = NULL;
int K = 10;
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:
12 -> 11 -> 10 -> 4 -> 3 -> 2 -> 1 ->
Linked List after deletion:
12 -> 11 -> 10 ->

## Conclusion

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