# Python Program For Writing A Function To Delete A Linked List

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

Implementation:Â

## Python3

 `# Python3 program to delete all ``# the nodes of singly linked list `` ` `# Node class ``class` `Node: `` ` `    ``# Function to initialize the  ``    ``# node object ``    ``def` `__init__(``self``, data): `` ` `        ``# Assign data ``        ``self``.data ``=` `data `` ` `        ``# Initialize next as null   ``        ``self``.``next` `=` `None`  ` ` ` ` `# Constructor to initialize the  ``# node object ``class` `LinkedList: `` ` `    ``# Function to initialize head ``    ``def` `__init__(``self``): ``        ``self``.head ``=` `None`` ` `    ``def` `deleteList(``self``): `` ` `        ``# Initialize the current node ``        ``current ``=` `self``.head ``        ``while` `current: `` ` `            ``# Move next node ``            ``prev ``=` `current.``next`  ` ` `            ``# Delete the current node ``            ``del` `current.data `` ` `            ``# Set current equals prev node ``            ``current ``=` `prev `` ` `        ``# In python garbage collection happens ``        ``# therefore, only self.head = None ``        ``# would also delete the link list  `` ` `    ``# Push function to add node in  ``    ``# front of llist ``    ``def` `push(``self``, new_data): `` ` `        ``# Allocate the Node & ``        ``# Put in the data ``        ``new_node ``=` `Node(new_data) `` ` `        ``# Make next of new Node as head ``        ``new_node.``next` `=` `self``.head `` ` `        ``# Move the head to point to the  ``        ``# new Node ``        ``self``.head ``=` `new_node `` ` `# Use push() to construct list ``# 1-> 12-> 1-> 4-> 1 ``if` `__name__ ``=``=` `'__main__'``: `` ` `    ``llist ``=` `LinkedList() ``    ``llist.push(``1``) ``    ``llist.push(``4``) ``    ``llist.push(``1``) ``    ``llist.push(``12``) ``    ``llist.push(``1``) `` ` `    ``print``(``"Deleting linked list"``) ``    ``llist.deleteList() `` ` `    ``print``(``"Linked list deleted"``) ``# This code is contributed by Shrikant13 `

Output:

```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!

Previous
Next
Share your thoughts in the comments
Similar Reads