[Python 3.8]
When removing a node in a linked list, can the next
node simply be changed?
Here, we "delete" Node 1, simply by changing the pointer.
Coming from a C++ world, this makes me a little nervous. Will the memory for Node 1 be reclaimed automatically, since there are no references thereto? What exactly happens to Node 1?
Before
[Sentinel] -> [Node 0] -> [Node 1] -> [Node 2] -> [Node 3] -> None
After
[Sentinel] -> [Node 0] -┐ [Node 1] -┬-> [Node 2] -> [Node 3] -> None
└-----------┘
Is this legit?
Minimal, complete, verifiable example
def delete(self, val):
n = self.sentinel
while n.next != None:
if n.next.data == val:
n.next = n.next.next # reassign pointer - no del, free, delete, or the like.
return
n = n.next