deleteLinkedList is doing far more work than it needs to.
del current.data removes the attribute from the
Node object, but that is not necessary. You rarely want to delete attributes from objects.
The only thing that’s necessary to clear the list and allow the memory to be freed is:
def deleteLinkedList(self): self.head = None
None, you’ve ensured that the nodes it held previously can no longer be accessed (assuming you didn’t store references to them elsewhere). Python will see this and automatically free the memory associated with the nodes.
If you were following this guide, I’d take it with a grain of salt. I can’t see why they’d possibly recommend using
del there, unless they had a plan to reuse the node structures later for later insertions; but that’s unlikely, and likely wouldn’t be beneficial anyways since
Nodes are so cheap to allocate.
CLICK HERE to find out more related problems solutions.