我偶然发现了这段代码,它应该删除链表的最后一个元素。我不明白如何通过修改局部变量来修改类属性:
class LinkedList {
constructor() {
this.head = null;
}
removeLast() {
if (!this.head) {
return;
}
if (!this.head.next) {
this.head = null;
return;
}
let previous = this.head;
let node = this.head.next;
while (node.next) {
previous = node;
node = node.next;
}
previous.next = null;
}
}
有什么解释或链接可以更好地理解这个主题吗?非常感谢。
问题中的代码修改对象引用。
与基元值不同,两个变量可以引用同一对象。因此,使用任何对象引用修改对象都将修改实际对象,并且这些更改将反映在所有对象引用中。
示例:
下面的代码片段显示了一个示例:
const obj = { name: 'John' };
const obj2 = obj;
obj2.name = 'Mike';
console.log(obj);
在上面的代码示例中,obj2.name
被更改,但是当obj
被记录在最后一行时,name
属性的值被更改为"0";迈克";。这是因为obj
和obj2
都指向内存中相同的对象。
要理解问题中的代码,您需要记住上面的代码示例,并了解它是如何工作的。
以下是解释removeLast()
方法如何工作的步骤:
-
检查列表是否为空。如果是,则从函数返回,因为没有任何内容可删除。
if (!this.head) { return; }
-
如果链表中只有一个节点,则使
head
指向null
,然后从函数返回。if (!this.head.next) { this.head = null; return; }
-
现在,我们需要遍历链表,到达链表中倒数第二个节点。当我们到达倒数第二个节点时,我们可以将倒数第二节点的
next
指向null
。这将删除对最后一个节点的任何引用。// create a temporary pointer to the first node // in the linked list let previous = this.head; // create a temporary pointer to the second node // in the linkedlist. "this.head.next" could be "null" // if there's only 1 node in the linkedlist let node = this.head.next; // traverse the linkedlist until "node.next" is not "null" while (node.next) { // point "previous" to the node that is pointed // to by "node" variable previous = node; // update "node" variable to point the node that // is next to the node that is currently pointed to by "node" // variable node = node.next; }
-
在第三步之后,
previous
将指向链表中倒数第二个节点。最后,倒数第二个节点的next
被设置为null
。这样做将删除最后一个节点。previous.next = null;