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.