educative.io

Alternate "removeNode" method implementation

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;
    }
  }

Hey @Stanislav_Dzhus

In order to find the position of the target node to be removed, we always have to start traversing the list from the start i.e. Head. The solution we provided will also stop when the target node is found, there’s a break statement at the end of the while loop. We appreciate your solution and it is correct. For the tail case, we will update the lesson.

Happy learning,