Open In App
Related Articles

Python Program For Writing A Function To Delete A Linked List

Like Article
Save Article
Report issue

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



# 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 = data
        # Initialize next as null  = 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 =  
            # Delete the current node
            # 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 = 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()
    print("Deleting linked list")
    print("Linked list deleted")
# This code is contributed by Shrikant13



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!

Last Updated : 08 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads