简体   繁体   中英

why the push method works in this Queue using javascrip

can someone please explain to how push(val) method works? I can't understand the logic. I don't know how this works, why it works.

class Node {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
};

class Queue {
    constructor() {
        this.first = null;
        this.last = null;
        this.length = 0;
    }

    push(val) {
        const temp = new Node(val)
        if(this.last === null) {
            this.first = temp
            this.last = temp
        } else {
            this.last.next = temp
            this.last = temp
        }
        this.length++;
        console.log(this)
    }
}

const queue = new Queue();
queue.push('Joy');
queue.push('Matt');
queue.push('Pavel');

This is a linked list:

在此处输入图片说明

So, initially, first (Head in the image) and last elements are null:

this.first = null;
this.last = null;
this.length = 0;

At this point, both are pointing to null.

If you add a new element, and if last is null, it knows that this is the initial state, which means, no element in the queue, so add the very first element to the queue and make first and last point to the same object, because there's only one at this point:

if(this.last === null) {
    this.first = temp
    this.last = temp
}

If you add another element, first check if there's any element in the queue (by checking the validity of last ) and if there is, add it to the end of the queue by:

else {
    this.last.next = temp
    this.last = temp
}

To explain it further, it does the following:

  • this.last is pointing to the last element of the queue (as of before adding the new element), so updates its next property to point to the new element.
  • Then, update this.last to point to the new last element, which is being added.
  • Also, note that at this point, its next pointer is pointing to null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM