Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么push方法使用javascrip在这个队列中工作_Javascript_Linked List - Fatal编程技术网

Javascript 为什么push方法使用javascrip在这个队列中工作

Javascript 为什么push方法使用javascrip在这个队列中工作,javascript,linked-list,Javascript,Linked List,有人能解释一下推送(val)方法是如何工作的吗?我不明白逻辑。我不知道这是怎么回事,为什么会这样 class Node { constructor(val) { this.val = val; this.next = null; } }; class Queue { constructor() { this.first = null; this.last = null; this.lengt

有人能解释一下推送(val)方法是如何工作的吗?我不明白逻辑。我不知道这是怎么回事,为什么会这样

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');
这是一个链接列表:

因此,最初,first(图像中的Head)和last元素为null:

this.first = null;
this.last = null;
this.length = 0;
此时,两者都指向null

如果添加新元素,并且
last
为null,则它知道这是初始状态,这意味着队列中没有元素,因此将第一个元素添加到队列中,并使
first
last
指向同一对象,因为此时只有一个:

if(this.last === null) {
    this.first = temp
    this.last = temp
}
如果添加其他元素,首先检查队列中是否有任何元素(通过检查
last
的有效性),如果有,则通过以下方式将其添加到队列末尾:

else {
    this.last.next = temp
    this.last = temp
}
为了进一步解释,它执行以下操作:

  • this.last
    指向队列的最后一个元素(在添加新元素之前),因此更新其
    next
    属性以指向新元素
  • 然后,更新
    this.last
    以指向正在添加的新的last元素
  • 另外,请注意,此时,其
    next
    指针指向
    null

看看这里->但我不知道为什么。first等于Joy=>Matt=>Pavel
这个。first
永远等于
Joy