class Node {
constructor(value){
this.value = value;
this.next = null;
}
}
class Queue{
constructor(){
this.first = null;
this.last = null;
this.length = 0;
}
enqueue(value){
const newNode = new Node(value)
if(this.length === 0){
this.first = newNode;
this.last = newNode;
} else {
this.last.next = newNode;
this.last = newNode;
}
this.length++;
return this;
}
}
const myQueue = new Queue();
myQueue.enqueue('a')
myQueue.enqueue('b')
Here I am implementing Queue with linkedlists. In else block of enqueue() method i am not assigning anything to this.first i am only assigning to this.last
How my this.first if changing.
Please have a look.
How this.first is changing without even touching it.
Actually the answer is correct but, I am not able to understand the logic.
this.last.nextbut when you insertbthis.last===this.first.this.first = newNode; this.last = newNode;. Changingthis.firstchanges properties onnewNode-- so does changingthis.last.