Home > Blockchain >  why is this linked-list add method working?
why is this linked-list add method working?

Time:04-26

I have created this method to add a number into a linked list, but I dont really understand why it is working.

If you take a look at the code bellow you will notice I created a variable named "current", which is set with the content of this.head, till then everything works perfectly but I dont understand why this.head is updating with the value of the current variable if I havent tell Javascript to do so.

this is my code, Ill really apreciate the help you guys can give me

class Node {
  constructor(value, next_node = null) {
    this.value = value;
    this.next_node = next_node;
  }
}

class LinkedList {
  // setup head and tail
  constructor() {
    this.head = null;
    this.length = 0;
  }
  
  add(number) {
    let node = new Node(number)
    if(this.head === null){
      this.head = node;
    } else {
     let current = this.head;
     while(current.next_node !== null){
       current = current.next_node   
     }
      current.next_node = node;
      console.log(this.head)
    }
    this.length  
  }
  
  get(index) {
  }
}

const ll = new LinkedList();
ll.add(2)
ll.add(3)
ll.add(5)

CodePudding user response:

It may help to visiualise the process:

Once you have created the list with const ll = new LinkedList(), we can represent the situation as:

 ll
  ↓
┌────────────┐  
│ head: null │
│ length: 0  │
└────────────┘

Now we execute ll.add(2), which equates this with ll and we perform let node = new Node(number). That can be depicted as:

 ll/this           node
  ↓                 ↓
┌────────────┐    ┌─────────────────┐
│ head: null │    │ value: 2        │
│ length: 0  │    │ next_node: null │
└────────────┘    └─────────────────┘

The if condition is true, so this.head = node is executed, and finally this.length . The call to add ends, and so the node variable is out of scope:

 ll/this
  ↓
┌────────────┐    ┌─────────────────┐
│ head: ────────           
  • Related