Write a function to delete a Linked List


The Java code provided demonstrates how to delete a linked list by setting the head to null.

  • The code defines a class named Function_Delete with an inner class Node representing a node in a linked list. Each node contains a String data value and a reference to the next node.
  • The Function_Delete class has a head member variable which represents the head of the linked list.
  • The deleteList method is used to delete the entire linked list. It simply sets the head to null, effectively removing all the nodes in the linked list from memory.
  • The push method is used to add new nodes to the front of the linked list. It takes a String value as input, creates a new node with the input value, and sets the next reference of the new node to the current head, making it the new head of the linked list.
  • Inside the main method, a Function_Delete object named col is created, which represents the linked list.
  • Several nodes with String values "Orange", "Red", "Pink", "Blue", "Green", and "Yellow" are added to the col linked list using the push method.
  • The code then prints a message "Deleting the Linkedlist.." to indicate that the linked list is being deleted.
  • The deleteList method is called, which sets the head of the linked list to null, effectively deleting the entire linked list.
  • Finally, the code prints a message "Linked list Deleted.." to indicate that the linked list has been deleted.
  • Note that deleting the linked list in this way simply sets the head to null, but the nodes in the linked list are not explicitly removed from memory. In Java, objects that are no longer reachable by any references are eligible for garbage collection, and the memory occupied by them will be reclaimed by the JVM at some point in the future.

Source Code

class Function_Delete
{
	Node head;
	class Node
	{
		String data;
		Node next;
		Node(String d)
		{
			data = d; next = null;
		}
	}
	void deleteList()
	{
		head = null;
	}
 
	public void push(String val)
	{
		Node new_node = new Node(val);
		new_node.next = head;
		head = new_node;
	}
 
	public static void main(String [] args)
	{
		Function_Delete col = new Function_Delete();
		col.push("Orange");
		col.push("Red");
		col.push("Pink");
		col.push("Blue");
		col.push("Green");
		col.push("Yellow");
 
		System.out.println("Deleting the Linkedlist.. ");
		col.deleteList();
		System.out.println("Linked list Deleted.. ");
	}
}

Output

Deleting the Linkedlist..
Linked list Deleted..

Example Programs