0

I am implementing a simple singly linked list in Javascript.

class Node {
   constructor(data) {
      this.data = data;
      this.next = null;
   }
}

class LinkedList {
   constructor() {
      this.head = null;
   }
}

I initially wrote an appendNode method like so:

appendNode(data) {
   const node = new Node(data);
   let curr = this.head;

   if (curr) {
      while (curr.next) curr = curr.next;
      curr.next = node;
   } else curr = node;
}

This does not work, head is never set, the LinkedList does not get built out with repeated calls to appendNode.

Rewriting appendNode like so:

appendNode(data) {
   const node = new Node(data);

   if (this.head) {
      let curr = this.head;

      while (curr.next) curr = curr.next;
      curr.next = node;
   } else this.head = node;
}

Does work. I suspect this has something to do with how Javascript handles object references, but searching around for other implementations of LinkedList in JS or the technical details of JS object references has borne no fruit.

Fam
  • 580
  • 1
  • 7
  • 29
  • I'm confused. In the first example `this.head` is never being set in the code. Where did you expect it to be set? – evolutionxbox Feb 02 '21 at 15:24
  • 1
    The main problem is that with `let curr = this.head;` the variable `curr` is not some sort of *reference* to `this.head`, it's just the *value* of `this.head` at the point of time the variable was created. Setting `curr` does not change what `curr` was derived from, so `this.head` remains unchanged. There is no link maintained between the two. – VLAZ Feb 02 '21 at 15:26
  • 1
    It's not an object references issue, you simply didn't set `this.head` in the first `appendNode()`. A common technique, add this line after you create a new node: `this.head = this.head || node` – terrymorse Feb 02 '21 at 15:42

0 Answers0