C++ - Delete all nodes of the Circular Doubly Linked List
Deleting all nodes of a circular doubly linked list requires traverse through the list and deleting each node one by one. It requires creating a current node pointing to the next of head. Delete the current node and move to the next node using temp node. Repeat the process till the current node becomes head. At last, delete the head.
The function deleteAllNodes is created for this purpose. It is a 3-step process.
void deleteAllNodes() { if(head != NULL) { //1. if head is not null create a temp node // and current node pointed to next of head Node *temp, *current; current = head->next; //2. if current node is not equal to head, delete the // current node and move current to next node using temp, // repeat the process till the current reaches the head while(current != head) { temp = current->next; free(current); current = temp; } //3. Delete the head free(head); head = NULL; } cout<<"All nodes are deleted successfully.\n"; }
The below is a complete program that uses above discussed concept of deleting all nodes of a circular doubly linked list which makes the list empty with size zero.
#include <iostream> using namespace std; //node structure struct Node { int data; Node* next; Node* prev; }; class LinkedList { private: Node* head; public: LinkedList(){ head = NULL; } //Add new element at the end of the list void push_back(int newElement) { Node* newNode = new Node(); newNode->data = newElement; newNode->next = NULL; newNode->prev = NULL; if(head == NULL) { head = newNode; newNode->next = head; newNode->prev = head; } else { Node* temp = head; while(temp->next != head) temp = temp->next; temp->next = newNode; newNode->next = head; newNode->prev = temp; head->prev = newNode; } } //delete all nodes of the list void deleteAllNodes() { if(head != NULL) { Node *temp, *current; current = head->next; while(current != head) { temp = current->next; free(current); current = temp; } free(head); head = NULL; } cout<<"All nodes are deleted successfully.\n"; } //display the content of the list void PrintList() { Node* temp = head; if(temp != NULL) { cout<<"The list contains: "; while(true) { cout<<temp->data<<" "; temp = temp->next; if(temp == head) break; } cout<<endl; } else { cout<<"The list is empty.\n"; } } }; // test the code int main() { LinkedList MyList; //Add four elements in the list. MyList.push_back(10); MyList.push_back(20); MyList.push_back(30); MyList.push_back(40); //Display the content of the list. MyList.PrintList(); //delete all nodes of the list MyList.deleteAllNodes(); //Display the content of the list. MyList.PrintList(); return 0; }
The above code will give the following output:
The list contains: 10 20 30 40 All nodes are deleted successfully. The list is empty.