How to Create a Destructor for Linked List in C++?

How to Create a “Destructor for Linked List in C++”?

Are you getting trouble creating a “destructor for linked list in C++” and need to know how to create one for your software? Or do you want to know about creating a destructor for the Doubly Linked List and circular linked list in C++?

A linked list is one of the linear data structures with better features than an array. In this article, we discuss linked lists and explain how to create destructors for essential linked lists. This article has several simple examples demonstrating how to code destructors for different linked lists and their advantages. 

Now without any further delay, let’s dive deep into the article.

 

 

What is a Linked List in C++?

A linked list is a collection of nodes in which each node points next node. It is the most favorite structure after the array data structure. Just like an array linked list is another data structure, a linked list is much better than an array in many situations. 

A linked list is a non-contiguous memory structure that is dynamic in size, which makes it much easier to insert a new node or delete any existing node.

Each node in the linked list contains two parts: data and a reference link that points to the next node, but the last node points to Null

Following are the key types of linked lists in C++; let’s discuss each along with examples:

  1. Singly linked list
  2. Doubly linked list
  3. Circular linked list

 

 

What is a Destructor for Linked List in C++?

A destructor is a method invoked automatically when the object goes out of scope or we explicitly call it to delete the linked list. It is used to remove all nodes of the linked list. A destructor doesn’t have any input parameters and no return type. 

Like a constructor, a destructor has the same name as the class but is preceded by a tilde sign(~). If a class doesn’t have a user-defined destructor method, then the class has an implicit destructor method which is blank. In a user-defined destructor, we iterate through the linked list and remove all the nodes one by one. Now have a look at destructor coding:

 

Code 

~linklist()                

{

Node* current = head;            

while( current != NULL )          

   {

      Node* temp = current;          

      current = current->next;      

      delete temp;                  

   }

}


 

Now, we will discuss destructors for single, doubly, and circular linked lists one by one with the help of simple and appropriate examples.

 

 

How to Create a Destructor for Singly Linked List in C++?

The singly-linked list is also known as one way chain in which we can only traverse in one direction. In other words, we can not traverse the list in the reverse direction. In a singly linked list, each link has only one pointer that points to the next node, and the last node point to Null. To write its user-defined destructor, we have to start deleting each node one by one till the last node. Now lets us understand this concept with the help of a simple example:

 

Code

#include <iostream>

using namespace std;




// Structure of Single Node

struct node                          

{

   int data;                          

   node* next;                        

};




// Class of singly linked list 

class singlylinklist

{

   private:

   node* head;                    

   public:

    

    // Singly linked list constructor automatically runs

    // When an object is created

    singlylinklist()                      

    { 

        head = NULL; 

        

    }




// Insert function used to insert a new node in the Linked list  

void insert(int d)        

{

    node* newnode = new node;          

    newnode->data = d;                

    newnode->next = head;            

    head = newnode;              

}




// Print Singly linked list

void print()

{

   node* current = head;            

    

    while( current != NULL )        

   {

    cout<<current->data<<endl;  

    current = current->next;        

   }

}




//destructor of linked list

// Explicitly called when the object of the class goes out of scope

~singlylinklist()                

{

   node* current = head;            

    

    while( current != NULL )          

   {

      node* temp = current;          

      current = current->next;      

      delete temp;                  

   }

}

};





int main()

{

    // As we create an object of a singly linked list 

    // constructor will be called automatically

    singlylinklist sl;      




    // Insert 5 values in Linked list

    sl.insert(34);    

    sl.insert(19);

    sl.insert(4);

    sl.insert(50);

    sl.insert(10);




    // Print Singly Linked list on the screen

    sl.print();    




   return 0;

}

 

Output

10

50

4

19

34

 

 

How to Create a Destructor for Doubly Linked List in C++?

The doubly-linked list is also known as two way chain in which we can traverse in both directions. In other words, we can traverse the list in the reverse direction. In a doubly linked list, each node has two pointers. 

One pointer is used to point to the next node, and the other points to the previous node; in the doubly linked list, the previous pointer of the first node and the last node’s next pointer point to Null. 

To write its user-defined destructor, we have to start deleting each node until the last node. Now let’s understand the concept of the destructor of a doubly linked list with the help of the example:

 

Code

#include <iostream>

using namespace std;




//node structure

struct Node {

  int data;

  Node* next;

  Node* prev;

};




class DoublyLinkedList {

  private:

    Node* head;

  public:

    DoublyLinkedList(){

      head = NULL;

    }

 

    //Add a new value at the end of the list

    void insert(int newdata) {

      Node* newNode = new Node();

      newNode->data = newdata;

      newNode->next = NULL;

      newNode->prev = NULL; 

      if(head == NULL) {

        head = newNode;

      } else {

        Node* temp = head;

        while(temp->next != NULL)

          temp = temp->next;

        temp->next = newNode;

        newNode->prev = temp;

      }    

    }



    //display the content of the list

    void print() {

      Node* temp = head;

      if(temp != NULL) {

        while(temp != NULL) {

          cout<<temp->data<<endl;

          temp = temp->next;

        }

        cout<<endl;

      } else {

        cout<< "The doubly linked list is empty." <<endl;

      }

    }    

    

    //destructor of doubly linked list

    // Automatically run when object scope ends

    ~DoublyLinkedList() {

      Node* temp = new Node();

      while(head != NULL) {

        temp = head;

        head = head->next;

        delete temp;

      }

      cout<<"All nodes are deleted successfully.\n";

    }


};



// Main function create an object of doubly linked list

int main() {

  DoublyLinkedList DList;



  //Insert five values in the doubly linked list.

  DList.insert(12);

  DList.insert(15);

  DList.insert(38);

  DList.insert(30);

  DList.insert(5);




    cout<< "The Doubly linked list contains: "<<endl;

  // Print the Doubly linked list on the screen.

  DList.print();

  return 0; 

}

 

 

How to Create a Destructor for Circular Linked List in C++?

The circular linked list traverses one way, just like a singly linked list, but it is visualized as a chain of nodes along with the last node’s next pointer pointing to the head node.

Now with the help of a simple example, lets us understand the destructor of a circular linked list:

 

Code

#include <iostream>

using namespace std;


// Structure of a Node

struct Node {

    int data;

    Node* next;

};


// Circular linked list Class

class CircularLinkedList {

  private:

    Node* head;

  public:

  // constructor of the class

    CircularLinkedList()

    {

      head = NULL;

    }


    // Insert new Data at the end of the list

    void Insert(int d) {

      Node* addNode = new Node();

      addNode->data = d;

      addNode->next = NULL; 

      if(head == NULL) {

        head = addNode;

        addNode->next = head;

      } 

      else 

      {

        Node* t = head;

        while(t->next != head)

        {

          t = t->next;

        }

        t->next = addNode;

        addNode->next = head;

      }    

    }



    //Print the Circular linked list

    void Print() {

      Node* t = head;

      if(t != NULL) {

        while(true) {

          cout<<t->data<<endl;

          t = t->next;

          if(t == head) 

            break;

        }

        cout<<endl;

      } 

      else 

      {

        cout<< "The Circular linked list is empty." <<endl;

      }

    }   

    

    //Destructor of Circular Linked List

    ~CircularLinkedList() 

    {     

      Node* nodeToDelete;

      Node* temp;

      temp = head;        

      if(temp != NULL) {

        while(temp->next != head) 

        {

            nodeToDelete = temp->next;

            temp->next = temp->next->next;

            delete nodeToDelete;

        }

    

        if (head != NULL)

        {

        delete head;

        head = NULL;

        }

      }

      cout<< "The Circular linked list is empty." <<endl;

    }

};


    // Main function

int main() {

    // Create object of CircularLinkedList Class

    CircularLinkedList CList;


    //Insert four elements in the circular linked list.

    CList.Insert(50);

    CList.Insert(10);

    CList.Insert(32);

    CList.Insert(35);
  

    cout<<"The list contains: "<<endl;

    // Print Circular linked list on the screen

    CList.Print();
  

  return 0; 

  //destructor is called automatically here

  // Scope of CList object ends here

}

 

 

Conclusion

To conclude, this article is about the destructor for linked lists in C++. We’ve discussed a destructor in C++ and the different types of destructors like singly, doubly, and circular linked lists in C++.

Remember, the destructors are always invoked explicitly neither they take parameters nor return value. With the help of a destructor, we minimize buffer overflows. We use a user-defined linked list destructor to deallocate the memory of a linked list object. 

Let’s have a quick review of the topics discussed in this article.

  1. What is a linked list?
  2. What is the destructor used for in the linked list?
  3. How to write a user-defined destructor for the linked list?
  4. How to write a user-defined destructor for the doubly linked list?
  5. How to write a user-defined destructor for the circular linked list?

Thank you for reading! If you found this article beneficial, don’t forget to share and comment below👇. 

Happy coding. 👍

 

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts
Total
0
Share