# Delete all the nodes from the list that are greater than x 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 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 greater than x or not.

• If the current data is greater than x, 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;
};
Node* getNewNode(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void deleteGreaterNodes(Node** head_ref, int x) {
Node *temp = *head_ref, *prev;
if (temp != NULL && temp->data > x) {
free(temp);
}
while (temp != NULL) {
while (temp != NULL && temp->data <= x) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
return;
}
prev->next = temp->next;
delete temp;
temp = prev->next;
}
}
cout << head->data << " -> ";
}
}
int main() {
Node* head = getNewNode(1);
int x = 3;
cout << "Linked List before deletion:" << endl;
cout << "\nLinked List after deletion:" << endl;
return 0;
}

## Output

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

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

## Conclusion

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