1

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?

2
  • 1
    its because by the time you've called size2 its on next therefore null Commented Jun 5, 2018 at 17:15
  • In the size2() method because of using the variable node mutation is not happening why is that? Commented Jun 5, 2018 at 17:30

1 Answer 1

1

In size2(), you are not mutating this.head because you first copy the reference in a local variable. Since in the while loop you are mutating the local node = node.next starting here nodeand this.head are not linked any more. It's the eternal Value/Reference pitfall.

Here is a related article.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.