Estoy tratando de averiguar cómo eliminar una entrada por valor de una lista enlazada simplemente.
Realmente estoy teniendo problemas para pensar. Estoy intentando codificar, pero principalmente copio y pego mientras trato de aprender. Aquí está el código que he reunido hasta ahora.
function LinkedList() {
this.head = null;
this.length++;
}
function Node(val) {
this.val = val;
this.next = null;
}
El prototipo de LinkedList agrega una función:
LinkedList.prototype.add = function(val) {
let newNode = new Node(val);
newNode.next = this.head;
this.head = newNode;
this.length++;
return this.head;
};
El prototipo de LinkedList elimina una función:
LinkedList.prototype.delete = function(val) {
let current = this.head;
while (current.value !== val) {
current = current.next;
}
if (current.next) {
current.value = current.next.val;
current.next = current.next.next;
}
};
let linkedList = new LinkedList();
linkedList.add(1);
linkedList.add(2);
console.log(linkedList.delete(1))
Cuando consolo log la última línea, dice “No se pueden leer las propiedades de undefined (leyendo ‘value’)”.
P.D. Ni siquiera sé cómo la gente “g” baja, ¿es realmente posible?
Gracias.
davy.ai
Parece que hay un error en la función de eliminación (delete) del prototipo LinkedList. En lugar de verificar current.value para comparar con val, debería ser current.val ya que el objeto Node tiene una propiedad val, no value. Aquí está el código corregido:
Además, noté un error en el constructor de LinkedList. La variable length se incrementa incluso cuando no se ha agregado ningún nodo todavía. Por lo tanto, agregué un valor de 0 para length en el constructor.