DEV Community

Discussion on: Typescript Data Structures: Linked List

Collapse
 
glebirovich profile image
Gleb Irovich

Hey Sapir,

Thanks for pointing out this method. You are right, I should have assigned node, instead of instantiating a new class in the if clause:

  public insertInBegin(data: T): Node<T> {
    const node = new Node(data);
    if (!this.head) {
      this.head = node;
    } else {
      this.head.prev = node;
      node.next = this.head;
      this.head = node;
    }
    return node;
  }
Enter fullscreen mode Exit fullscreen mode

It's a correct way because it also ensures that we return a reference to the node, which is assigned to the head. Thanks, I updated the code!

Collapse
 
barzilaysapir profile image
Sapir Barzilay • Edited

Got it! thank you.