In existing removeNode
implementation we always traverse from beginning to the end regardless of target node position. Why can’t we stop when we found and deleted the node? Also, if linked list length equals 1 (and this element is deleted), this.tail
will still have this element. My solution is:
removeNode(data) {
let previousNode = this.head;
let currentNode = this.head;
while (currentNode) {
if (currentNode.data === data) {
if (currentNode === this.head) {
this.head = currentNode.next;
}
if (currentNode === this.tail) {
if (this.head === null) {
this.tail = null;
} else {
this.tail = previousNode;
}
}
previousNode.next = currentNode.next;
break;
}
previousNode = currentNode;
currentNode = currentNode.next;
}
}