1
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.

6
  • You are assigning to this.last.next but when you insert b this.last === this.first. Commented Jun 16, 2019 at 5:13
  • How is becomes this.last === this.first ? Commented Jun 16, 2019 at 5:15
  • I didn't mention anywhere? Commented Jun 16, 2019 at 5:16
  • You assign both to the same reference: this.first = newNode; this.last = newNode;. Changing this.first changes properties on newNode -- so does changing this.last. Commented Jun 16, 2019 at 5:16
  • Okk. got it. Thanks Commented Jun 16, 2019 at 5:18

1 Answer 1

5

Look at these two lines:

this.first = newNode;
this.last = newNode;

You are setting the REFERENCE to this.first and this.last to the same object. Basically, this.first and this.last have the same memory address.

So, next time you are calling:

this.last.next = newNode;
this.last = newNode;

this.last.next modifies the object reference of the previous newNode, whose memory address is same as this.first. So, when you change in this.last it gets modified also in this.first.

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.