Linked List Singly Linked List

Java Algorithm – Write a function to delete a Linked List

Java Algorithm - Write a function to delete a Linked List - Linked List - Iterate through the linked list and delete all the nodes one by one.

Algorithm For C/C++: Iterate through the linked list and delete all the nodes one by one. Main point here is not to access next of the current pointer if current pointer is deleted.

In Java, automatic garbage collection happens, so deleting a linked list is easy. We just need to change head to null.

Java Programming:

// Java program to delete a linked list
class LinkedList
{
    Node head; // head of the list
 
    /* 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 */
        new_node.next = 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 below list
           1->12->1->4->1  */
 
        llist.push(1);
        llist.push(4);
        llist.push(1);
        llist.push(12);
        llist.push(1);
 
        System.out.println("Deleting the list");
        llist.deleteList();
 
        System.out.println("Linked list deleted");
    }
}
// This code is contributed by Rajat Mishra

Output:

 Deleting linked list
 Linked list deleted

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

See also  Python Algorithm- Delete a Linked List node at a given position

About the author

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment