2.2.3. ALGORITHMS & DATA STRUCTURES. LINKED LISTS. THE DELETE METHOD.
Igor Balitskyi
Backend Python Developer (Django, SQL), Founder, Developer & CEO of GPS Vehicle Monitoring System
In this method, we need to do two things. First, we need to find a cell with the specified value, and second, we need to keep track of the previous cell. As soon as we find the required entry, we just need to create a new link from the previous node to the node with the found values. After this, we can delete the object from memory. Let's examine the implementation in the Python programming language.
def delete(self, value):
'''
Delete an element based on its value.
Complexity: O(n).
'''
current = self.top.next_node
prev = self.top
while current is not None:
if current.value == value:
prev.next_node = current.next_node
return
prev = current
current = current.next_node
In the first lines, we set the current and previous elements. The previous element is initially set as the limiter. Next, we simply iterate through all the elements. If the values of an element match the one we are searching for, we just update the references. Furthermore, please note that in the delete methods, we return without the current cell. This is because of Python's garbage collection mechanism. After references to an object cease to exist, it is automatically deleted from memory. We stop referencing it in this line: prev.next_node = current.next_node, when we change the next_node in the previous element. Garbage collection works not only in Python but also in Java, C#, and other programming languages. However, in some languages like C++, you may need to explicitly delete a cell from memory, for example, by using a function like free(current). That concludes our discussion of singly linked lists. Next will be doubly linked lists.