Delete all the nodes from the list that are greater than x in C++

C++Server Side ProgrammingProgramming

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) {
      *head_ref = temp->next;
      free(temp);
      temp = *head_ref;
   }
   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;
   }
}
void printLinkedList(Node* head) {
   while (head) {
      cout << head->data << " -> ";
      head = head->next;
   }
}
int main() {
   Node* head = getNewNode(1);
   head->next = getNewNode(2);
   head->next->next = getNewNode(3);
   head->next->next->next = getNewNode(4);
   head->next->next->next->next = getNewNode(5);
   head->next->next->next->next->next = getNewNode(6);
   int x = 3;
   cout << "Linked List before deletion:" << endl;
   printLinkedList(head);
   deleteGreaterNodes(&head, x);
   cout << "\nLinked List after deletion:" << endl;
   printLinkedList(head);
   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.

raja
Published on 30-Dec-2020 11:29:17
Advertisements