
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete All Even Nodes from a Doubly Linked List in C++
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 even or not.
If the current data is even, 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.
#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; new_node->next = (*head_ref); if ((*head_ref) != NULL) { (*head_ref)->prev = new_node; } (*head_ref) = new_node; } void deleteNode(Node** head_ref, Node* del) { if (*head_ref == NULL || del == NULL) { return; } if (*head_ref == del) { *head_ref = del->next; } if (del->next != NULL) { del->next->prev = del->prev; } if (del->prev != NULL) { del->prev->next = del->next; } free(del); return; } void deleteEvenNodes(Node** head_ref) { Node* temp = *head_ref; Node* next; while (temp != NULL) { next = temp->next; if (temp->data % 2 == 0) { deleteNode(head_ref, temp); } temp = next; } } void printLinkedList(Node* head) { while (head != NULL) { cout << head->data << " -> "; head = head->next; } } int main() { Node* head = NULL; insertNode(&head, 1); insertNode(&head, 2); insertNode(&head, 3); insertNode(&head, 4); insertNode(&head, 5); insertNode(&head, 6); cout << "Linked List before deletion:" << endl; printLinkedList(head); deleteEvenNodes(&head); cout << "\nLinked List after deletion:" << endl; printLinkedList(head); }
Output
If you execute the above program, then you will get the following result.
Linked List before deletion: 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Linked List after deletion: 5 -> 3 -> 1 ->
Conclusion
If you have any queries in the tutorial, mention them in the comment section.