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.
Deleting linked list Linked list deleted
Time Complexity: O(n)
Auxiliary Space: O(1)