I am learning how to add node to the linked list. The following is the correct code:
class NodeList {
constructor(head = null){
this.head = head
this.addLast = function (data) {
let node = new Node(data)
console.log(curr)
if (this.head === null) {
return this.head = node
} else{
let curr = this.head
while(curr.next){
curr = curr.next
}
curr.next = node
}
}
}
}
Initially,
i wrote the code as such:
class NodeList {
constructor(head = null){
this.head = head
this.addLast = function (data) {
let node = new Node(data)
console.log(curr)
if (this.head === null) {
return this.head = node
} else{
let curr = this.head
while(curr.next){
curr = curr.next
}
curr.next = node
}
}
}
}
The main difference is at the if statement. Instead of
if(this.head === null) { return this.head = node}
I wrote
let curr = this.head
if(curr === null) { return curr = node}
However, the code doesn't work.
If I do something like
let nodeList = new Nodelist nodeList.addLast(2)
I expect to get head: Node {data: 2, next: null}. The first code achieved that purchase but the second code does not. I am confused why this is so. Both codes look the same. Can someone enlighten me?