【发布时间】:2020-08-21 14:15:21
【问题描述】:
我认为这段代码可以很好地创建一个链表并附加到它, 但我不明白下面我评论它的一小段代码请帮忙。
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor(value) {
this.head = new Node(value);
this.tail = this.head;
this.length = 1;
}
append(value) {
const newNode = new Node(value);
// how come that we did not even mention this.head and it keeps adding to it??
this.tail.next = newNode; //<<<<< can not figure this one
this.tail = newNode;
this.length++;
return this;
}
}
//test code
let myLinkedList = new LinkedList(10);
myLinkedList.append(5);
myLinkedList.append(16);
myLinkedList.append(14);
console.log(myLinkedList);
我试图理解的内容>>>
// instantiation
p = { a: 1, b: null };
c = p;
// what happens when i call append
node = { a: 2, b: null };
c.b = node;
console.log(p);
c = node;
node1 = { a: 3, b: null };
c.b = node1;
console.log(p);
c = node1;
node2 = { a: 4, b: null };
c.b = node2;
console.log(p);
c = node2;
我想知道c 如何准确访问p 对象中的最后一个b 属性,
每个 b 都有它自己的内存地址还是因为c 包含a: 4 所以当我说c.b 它访问b 与它有a: 4?
【问题讨论】:
-
因为在构造函数中有这个语句
this.tail = this.head; -
是的,我想过但还是不明白,你能解释一下吗
-
我的意思是当我们改变 this.tail.next 它改变 this.head 但是,当我们改变 this.tail this.head 不响应?怎么样?
-
当
LinkedList的新实例被创建时,this.tail是对this.head的引用(两个变量都指向同一个Node),那么,每次调用append,this.tail改为指向最新创建的Node。 -
感谢您的帮助,感谢您的帮助,我添加了一个可以更好地证明我的困惑的部分,请您检查一下!
标签: javascript data-structures linked-list