I wanted to implement a method which eliminates a node in between, that is, the method must eliminate the nodes that are in the intermediate positions and whose value is equal to the one passed as the second parameter
class LinkedList:
"""
Lista simplemente encadenada
Atributos
---------
__first: (Node) referencia al primer nodo de la lista
__len : (int) almacena el número de elementos de la lista
Clases
------
LinkedList.Node: clase para representar los nodos de la lista encadenada
"""
def __init__(self):
self.__first = None
self.__len = 0
def __len__(self):
return self.__len
class Node:
def __init__(self, value, next_node = None):
self.value = value
self.next_node = next_node
# NO MODIFIQUE código que está por encima
Method mentioned above
def eliminar_nodo(self, value):
current_node = self.__first
prev_node = current_node
while current_node is not None:
if current_node.value == value:
if current_node == self.__first:
self.__first = self.__first.next_node
self.__len -= 1
else:
prev_node.next_node = current_node.next_node
self.__len -= 1
prev_node = current_node
current_node = current_node.next_node
The problem comes when I try to delete a contiguous repeated intermediate element.
Lista original: [10, 14, 16, 16, 16, 19, 25]
nodo a eliminar: 16
resultado: [10, 14, 16, 19, 25]
output esperado: [10, 14, 19, 25]
The error is because when you delete an intermediate node you cannot make
prev_node
it the node deleted in the next iteration , ifcurrent_node
it has been deleted itprev_node
must continue to point to the node before the one deleted in the next iteration.What is happening now:
Green is
current_node
and blue isprev_node
. The last scheme the final result.What should happen:
Therefore the code should be: