Python Program For Writing A Function To Delete A Linked List
Last Updated :
08 Dec, 2021
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
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def deleteList( self ):
current = self .head
while current:
prev = current. next
del current.data
current = prev
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
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" )
|
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!
Share your thoughts in the comments
Please Login to comment...