Home > Software engineering >  JavaScript Data structure and algorithms Linked List Clarification
JavaScript Data structure and algorithms Linked List Clarification

Time:10-30

I'm just a little bit confuse here, I want to know what is really happening. I'm following a tutorial for DS&A for Javascript -> https://www.youtube.com/watch?v=BVJv_AiXSGg&t=495s (51:21 part). I'm asking it here because it wasn't mentioned in the tutorial.

Here is the class for Node:

class NodeClass {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

And here is the class for actual linked list:

class LinkedList {
  constructor(value) {
    const newNode = new NodeClass(value);

    this.head = newNode;
    this.tail = this.head;
    this.length = 1;
  }

  push(value) {
    const newNode = new NodeClass(value);

    this.tail.next = newNode;
    this.tail = newNode;

    this.length  ;

    return this;
  }
}

printing:

let myLinkedList = new LinkedList(7);
myLinkedList.push(4);

console.log(myLinkedList);

Now the tricky part for me and the one I really confused is the output

LinkedList {
  head: NodeClass { value: 7, next: NodeClass { value: 4, next: null } },
  tail: NodeClass { value: 4, next: null },
  length: 2
}

As you can see, the "next" property had an object value which is "{ value: 4, next: null }" But the one that I don't understand is I did not do "this.head.next", and yet it is working fine.

Can you please help me to understand what's going under the hood about this one.

Furthermore, if I push more more more data it works totally fine as expected. Thank you !

CodePudding user response:

This is because objects are referenced in javascript. What that means is that when you assign an object to a variable, and then assign it to another variable, both of them will point to the same object which means that if you update one, it will be reflected in other as well.

In the constructor of LinkedList, you can see that this.head and this.tail are both assigned to the same object newNode. So, when you push a new node in push, it is appending to tail and it also reflects in head because head points to the very root node and all other nodes are added as tails to the following nodes.

In your example, after push(4), the tail now points to the node with value 4. You can do another push, maybe push(42) and see that tail will keep pointing to the very last node and all the new nodes will keep appending to the next of the following nodes.

You can learn more about pass-by-reference in javascript.

  • Related