DEV Community

Discussion on: Typescript Data Structures: Linked List

Collapse
 
barzilaysapir profile image
Sapir Barzilay • Edited

Hi, great article.
I don't get it, why on insertToBegin of a double linked list,
if the list is empty you're using :
this.head = new Node(),
and on the same condition when insertAtEnd, you're using:
this.head = node.
or maybe it's just an example you can do it both ways?
Thought I got it at first but then I got a little confused, would like to clear this up!
Thanks.

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.