Facebook Page Twitter Page LinkedIn Page
× C++ Data Structures - Linked List Other Related Topics


Deleting all nodes of a linked list requires traverse through the list and deleting each node one by one. It requires creating a temp node pointing to the head then move the head to head next. After that delete the temp node. Repeat the process till the head becomes null.

The function deleteAllNodes is created for this purpose. It is a 2-step process.

void deleteAllNodes() {
  
  //1. create a temp node
  Node* temp = new Node();
  
  //2. if the head is not null make temp as head and 
  //   move head to head next, then delete the temp,
  //   continue the process till head becomes null
  while(head != NULL) {
    temp = head;
    head = head->next;
    free(temp);
  }

  cout<<"\nAll nodes are deleted successfully.";  
} 

The below is a complete program that uses above discussed concept of deleting all nodes of a linked list which makes the list empty with size zero.

#include <iostream>
using namespace std;

//node structure
struct Node {
    int data;
    Node* next;
};

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; 
      if(head == NULL) {
        head = newNode;
      } else {
        Node* temp = head;
        while(temp->next != NULL)
          temp = temp->next;
        temp->next = newNode;
      }    
    }
    
    //delete all nodes of the list
    void deleteAllNodes() {
      Node* temp = new Node();
      while(head != NULL) {
        temp = head;
        head = head->next;
        free(temp);
      }
      cout<<"\nAll nodes are deleted successfully.";  
    }

    //display the content of the list
    void PrintList() {
      Node* temp = head;
      if(temp != NULL) {
        cout<<"\nThe list contains: ";
        while(temp != NULL) {
          cout<<temp->data<<" ";
          temp = temp->next;
        }
      } else {
        cout<<"\nThe list is empty.";
      }
    }    
};

// 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.