[英]why the push method works in this Queue using javascrip
can someone please explain to how push(val) method works?有人可以解释一下 push(val) 方法是如何工作的吗? 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.此时,两者都指向 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:如果添加一个新元素,并且如果last
为 null,则它知道这是初始状态,这意味着队列中没有元素,因此将第一个元素添加到队列中并使first
和last
指向同一个对象,因为此时只有一个:
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:如果添加另一个元素,首先检查队列中是否有任何元素(通过检查last
的有效性),如果有,则通过以下方式将其添加到队列末尾:
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. this.last
指向队列的最后一个元素(在添加新元素之前),因此更新其next
属性以指向新元素。this.last
to point to the new last element, which is being added.然后,更新this.last
以指向新添加的最后一个元素。next
pointer is pointing to null
.另外,请注意,此时,它的next
指针指向null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.