In the below code size2() method working fine.But in size1() it is mutating the object and making it null.why such behavior is not happening in size2()?
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
}
insert(data) {
this.head = new Node(data, this.head);
}
size1() {
var counter = 0;
while (this.head) {
counter++;
this.head = this.head.next;
}
return counter;
}
size2() {
var counter = 0;
var node = this.head;
while (node) {
counter++;
node = node.next;
}
return counter;
}
}
var list = new LinkedList();
list.insert(35);
console.log(list);
console.log(list.size2());
To me both the method looks same. Is there any subtle difference in those methods?