Write a function to delete a Linked List in C++ Programming

C++Server Side ProgrammingProgramming

Here, we will create a function that will delete all elements of a linked list one by one.

In c/c++, there is no specific function to perform this task but in java, the automatic garbage collection is done to ease deleting linked list.

Now, let’s see the implementation of this program,


 Live Demo

#include <iostream>
using namespace std;
class Node{
   int data;
   Node* next;
void deleteLinkedList(Node** head_ref){
   Node* current = *head_ref;
   Node* next;
   while (current != NULL){
      next = current->next;
      current = next;
   *head_ref = NULL;
void push(Node** head_ref, int new_data){
   Node* new_node = new Node();
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
int main(){
   Node* head = NULL;
   push(&head, 25);
   push(&head, 10);
   push(&head, 5);
   push(&head, 90);
   push(&head, 68);
   cout<<"Elements of linked list : ";
   cout << "
Linked list deleted"; }


Elements of linked list : 68 90 5 10 25
Linked list deleted
Updated on 15-Jul-2020 06:21:31