Algoritmo para Python:
en Python, se realiza la recolección automática de basura, por lo que eliminar una lista vinculada es fácil. Solo necesito cambiar la cabeza a nulo.
Implementación:
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
Producción:
Deleting linked list Linked list deleted
Complejidad temporal: O(n)
Espacio auxiliar: O(1)
Consulte el artículo completo sobre Escribir una función para eliminar una lista vinculada para obtener más detalles.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA