Skip to content
Related Articles

Related Articles

Java Program For Writing A Function To Delete A Linked List

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 08 Dec, 2021

Algorithm For Java:
In Java, automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null.



// Java program to delete a linked list
class LinkedList
    // Head of the list
    Node head; 
    // Linked List node 
    class Node
        int data;
        Node next;
        Node(int d) 
            data = d; 
            next = null
    // Function deletes the entire 
    // linked list 
    void deleteList()
        head = null;
    // Inserts a new Node at front 
    // of the list. 
    public void push(int new_data)
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);
        // 3. Make next of new Node as head = head;
        // 4. Move the head to point to new Node 
        head = new_node;
    public static void main(String [] args)
        LinkedList llist = new LinkedList();
        // Use push() to construct list
        // 1->12->1->4->1  
        System.out.println("Deleting the list");
        System.out.println("Linked list deleted");
// This code is contributed by Rajat Mishra


Deleting linked list
Linked list deleted

Time Complexity: O(n) 
Auxiliary Space: O(1)

Please refer complete article on Write a function to delete a Linked List for more details!

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!