Delete all nodes in a linked list

Linked list each node are create dynamically in heap area. And each node can we contains many number of instance variables (for data fields and pointer fields). Therefore that is very important remove all linked list node when linked list are no longer need. Because that is are best way to utilize heap area memory and avoid memory overflow problem.

Suppose we are inserted the following (1,2,3,4,5,6) node in a sequence.

Here given code implementation process.

//C Program
//Delete all nodes from given linked list
#include<stdio.h>
#include <stdlib.h> //for malloc function

//create structure
struct Node{
  int data;
  struct Node*next;
};
//function prototype
void insert(struct Node**,int);
void display(struct Node*);
void delete_all(struct Node**);
//insert Node element
void insert(struct Node**head,int value){
  //Create dynamic node
  struct Node*node=(struct Node*)malloc(sizeof(struct Node));
  if(node==NULL){
    printf("Memory overflow\n");
  }else{
    node->data=value;
    node->next=NULL;
    if(*head==NULL){
      *head=node;
    }else{
      struct Node*temp=*head;
      //find last node
      while(temp->next!=NULL){
        temp=temp->next;
      }
      //add node at last possition
      temp->next=node;
    }
  }
}
//Display element of Node
void display(struct Node*temp){
  
  if(temp==NULL){
    printf("Empty linked list");
  }
  while(temp!=NULL){
    printf("%d  ",temp->data);
    temp=temp->next;
  }
}
//This function are remove all linked list node
void delete_all(struct Node**head){
  struct Node*free_node=NULL;
  while(*head!=NULL){
    free_node=*head;
    //head node are visit next upcoming node
    *head=free_node->next;

    free_node->next=NULL;
    free(free_node); //free node memory
    free_node=NULL;
  }
}
int main(){
  //create node pointer
  struct Node*head=NULL;
  //insert element of linked list

  insert(&head,1);
  insert(&head,2);
  insert(&head,3);
  insert(&head,4);
  insert(&head,5);
  insert(&head,6);
  printf("Before delete Linked List \n");
  //display all node
  display(head);

  delete_all(&head);

  printf("\nAfter Delete All Linked List Nodes\n");
  display(head);
  return 0;
}

Output

Before delete Linked List 
1  2  3  4  5  6
After Delete All Linked List Nodes
Empty linked list
//C++ Program 
//Delete all nodes from given linked list
#include<iostream>
using namespace std;

//create structure
struct Node{
  int data;
  struct Node*next;
};
class LinkedList{
  Node*head;//head node
  public:
    LinkedList();
    void insert(int);
    void display();
    void delete_all();
};
LinkedList::LinkedList(){
  head=NULL;
}
//insert node at end of linked list
void LinkedList::insert(int value){
    //Create dynamic node
  struct Node*node=new Node;
  if(node==NULL){
    cout<<"Memory overflow\n";
  }else{
    node->data=value;
    node->next=NULL;
    if(head==NULL){
      //base condition
      head=node;
    }else{
      Node*temp=head;
      while(temp->next!=NULL){
        temp=temp->next;
      }
      //add newly node at last
      temp->next=node;
    }
  }
}
//display all node value in linked list
void LinkedList:: display(){
  if(head==NULL){
    cout<<"Empty linked list";
  }
  else{
    Node*temp=head;
  
    while(temp!=NULL){
      //print node value
      cout<<temp->data<<" ";
      temp=temp->next;
    }
  }

}
//This function are remove all linked list nodes
void LinkedList:: delete_all(){
 
  Node*free_node=NULL;
  while(head!=NULL){
    free_node=head;
    //head node are visit next upcoming node
    head=free_node->next;

    free_node->next=NULL;
    delete free_node; //free node memory
    free_node=NULL;
  }

}
int main(){
 
  //create object
  LinkedList obj;
  //insert element of linked list
  obj.insert(1);
  obj.insert(2);
  obj.insert(3);
  obj.insert(4);
  obj.insert(5);
  obj.insert(6);
  cout<<"Before delete Linked List "<<endl;
  //display all node
  obj.display();

  obj.delete_all();

  cout<<"\nAfter delete Linked List Nodes"<<endl;
  obj.display();

  return 0;
}

Output

Before delete Linked List 
1 2 3 4 5 6 
After delete Linked List Nodes
Empty linked list
//Java Program
//Delete all nodes from given linked list
public class LinkedList{

  static class Node{
    int data;
    Node next;
  }
  static Node head;
  //Class constructors
  LinkedList(){
    head=null;
  } 
  //insert element
  public void insert(int value){
    //Create  node
    Node node=new Node();
    node.data=value;
    node.next=null;
    if(head==null) head=node;
    else{
      Node temp=head;
      //find last node
      while(temp.next!=null){
        temp=temp.next;
      }
      temp.next=node;
    }
    
  }
  //Display all Linked List elements
  public void display(){
    if(head!=null){
      System.out.print("Linked List Element :");
      Node temp=head;
      while(temp!=null){
        System.out.print("  "+temp.data);
        temp=temp.next;
      }
    }else{
      System.out.println("Empty Linked list"); 
    }
  }
  //This function are remove all linked list node
  public void deleteAll(){
 
    Node freeNode=null;
    while(head!=null){
      freeNode=head;
      //head node are visit next upcoming node
      head=freeNode.next;

      freeNode.next=null;
      freeNode=null; //free memory
  }

}

  public static void main(String[] args) {
    
    LinkedList obj=new LinkedList();
    obj.insert(1);
    obj.insert(2);
    obj.insert(3);
    obj.insert(4);
    obj.insert(5);
    obj.insert(6);
    System.out.print("Before delete Linked List \n");
    obj.display();
    obj.deleteAll();
    System.out.print("\nAfter delete Linked List \n");
    obj.display();
  }
}

Output

Before delete Linked List 
Linked List Element :  1  2  3  4  5  6
After delete Linked List 
Empty Linked list
#Python Program
#Delete all nodes from given linked list
class Node:
    def __init__(self,data):
        self.data=data
        self.next=None

#Create Class Linked    
class Linked:
    def __init__(self):
        #Assign default value
        self.head=None

    #insert new node to linked list  
    def insert(self,data):
        node=Node(data)
        node.next=None
        if self.head==None:
            self.head=node
        else:
            temp=self.head
            while temp.next!=None:
                temp=temp.next
            #add node    
            temp.next=node

    def display(self):
        if(self.head==None):
            print("Empty Linked List")
            return

        temp=self.head
     
        while(temp!=None):
          print(temp.data,end=" ")
          temp=temp.next
        print("\n")

    #delete all linked list nodes
    def deleteAll(self):
    	freeNode=None
    	while self.head:
    		freeNode=self.head
    		self.head=freeNode.next
    		freeNode=None
    		

def main():
    #Create Object of class Linked
    obj=Linked()
    #Perform Linked operation
    obj.insert(1)
    obj.insert(2)
    obj.insert(3)
    obj.insert(4)
    obj.insert(5)
    obj.insert(6)
    

    print("Before delete Linked List ")
    obj.display()

    obj.deleteAll()
    print("After delete Linked List ")
    obj.display()

if __name__=="__main__":
    main()

Output

Before delete Linked List 
1 2 3 4 5 6 

After delete Linked List 
Empty Linked List
//C# Program
//Delete all nodes from given linked list
using System;
//node class
public class Node{
	public  int data;
	public  Node next;
}
class MyLinkedList
{
	Node head;
	public MyLinkedList(){
		head=null;
	}
	//insert node of linked list
	public void insert(int data){
		Node newNode=new Node();
		newNode.data=data;
		newNode.next=null;
		if(head==null) head=newNode;
		else{
			Node temp=head;
			//get last node
			while(temp.next!=null){
				temp=temp.next;
			}
			//add new node
			temp.next=newNode;
		}
	}
	//display linked list nodes value
	public void display(){
		if(head==null){
			Console.Write("Empty List");
		}else{
			Node temp=head;
			while(temp!=null){
				Console.Write("  {0}",temp.data);
				temp=temp.next;
			}

		}
	}
	//This function are remove all linked list node
	public void deleteAll(){

		Node freeNode = null;
		while (head != null) {
			freeNode = head;
			//head node are visit next upcoming node
			head = freeNode.next;

			freeNode.next = null;
			freeNode = null; //free memory
		}
	}
	static void Main()
	{
		MyLinkedList obj=new MyLinkedList();
		obj.insert(1);
		obj.insert(2);
		obj.insert(3);
		obj.insert(4);
		obj.insert(5);
		obj.insert(6);
		Console.WriteLine("Before delete Linked List ");
		obj.display();
		obj.deleteAll();
		Console.WriteLine("\nAfter delete Linked List");
		obj.display();
	}
}

Output

Before delete Linked List 
  1  2  3  4  5  6
After delete Linked List
Empty List


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved