My LinkedList Class has two properties
- this.head
- this.size
this.head
is used to contain the list of objects. Simple logic says, if I update this.head
, its value should be updated. If I, however, assign its value to some other variable and then try to update that variable, then the original this.head shouldn't update.
Eg:
printElements(){
let current = this.head;
while(current){
console.log(current.data)
current = current.next;
}
};
But this piece of code contradicts that situation. I don't know why this.head
is getting updated here when it's not directly referenced.
insertAt(data, index){
if(index > 0 && index > this.size)
return
const node = new Node(data);
let current, previous;
current = this.head;
let count = 0;
while(count < index){
previous = current;
count++;
current = current.next;
}
node.next = current;
previous.next = node;
};
The entire piece of code
class Node{
constructor(data, next = null){
this.data = data;
this.next = next;
}
}
class LinkedList{
constructor(){
this.head = null;
this.size = 0;
};
insert(data){
this.head = new Node(data, this.head);
this.size++;
};
insertAt(data, index){
if(index > 0 && index > this.size)
return
const node = new Node(data);
let current, previous;
current = this.head;
let count = 0;
while(count < index){
previous = current;
count++;
current = current.next;
}
node.next = current;
previous.next = node;
};
printElements(){
let current = this.head;
while(current){
console.log(current.data)
current = current.next;
}
};
}