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!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
08 Dec, 2021
Like Article
Save Article