Elc*_*hin 6 javascript linked-list data-structures singly-linked-list
我尝试了解push()方法如何与 JS 中的 tails 一起使用。这是代码:
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.length = 0;
this.head = null;
this.tail = null;
}
push(val) {
const newNode = new Node(val)
if (this.head===null) { // happens only once
this.head = newNode;
this.tail = this.head;
} else {
this.tail.next = newNode; // this.a.next = b node???
this.tail = newNode;
}
this.length++
}
Run Code Online (Sandbox Code Playgroud)
具体来说,我不明白else该方法内部的部分push()。如果我们说,如何为每个nextahead分配一个新节点this.tail.next = newNode?head 和 tail 之间的关系在哪里以及this.tail.next = newNode我们如何访问head列表的属性?当我运行这段代码时,它工作得完全正确,但它让我感到困惑。
const myList = new SinglyLinkedList();
myList.push("111");
myList.push("222");
myList.push("333");
console.log(myList);
Run Code Online (Sandbox Code Playgroud)
输出:
SinglyLinkedList {
length: 3,
head: Node { val: '111', next: Node { val: '222', next: [Node] } },
tail: Node { val: '333', next: null } }
Run Code Online (Sandbox Code Playgroud)
\n\n如果我们说 this.tail.next = newNode ,如何为每个
\nnextahead分配一个新节点?head 和 tail 之间的关系在哪里?如何通过 this.tail.next = newNode 来访问列表的 head 属性?
让我们回到空列表。第一次添加节点时,我们进入if块,其中 和head都tail将引用同一个新节点。这意味着从那一刻起,无论您进行 mutate ,都tail将是 mutating head,因为它们引用同一个对象。
现在执行了第二个push,我们进入了else块。在那里,我们将新节点分配给next的属性tail。head但由于这是引用同一个对象,所以我们实际上head.next在这里设置!这种情况仅发生在第二个节点上push,因为在这次分配之后,tail会被分配一个新的引用(next),因此从那时起,它head会tail引用不同的节点。
以图形方式:
\n后push('111'):
head\n \xe2\x86\x93\n111\n \xe2\x86\x91\ntail\nRun Code Online (Sandbox Code Playgroud)\n当push('222'),之后this.tail.next = newNode;:
head\n \xe2\x86\x93\n111 \xe2\x86\x92 222\n \xe2\x86\x91\ntail\nRun Code Online (Sandbox Code Playgroud)\n...this.tail = newNode;在同一次推动之后:
head\n \xe2\x86\x93\n111 \xe2\x86\x92 222\n \xe2\x86\x91\n tail\nRun Code Online (Sandbox Code Playgroud)\n当push('333'),之后this.tail.next = newNode;:
head\n \xe2\x86\x93\n111 \xe2\x86\x92 222 \xe2\x86\x92 333\n \xe2\x86\x91\n tail\nRun Code Online (Sandbox Code Playgroud)\n...this.tail = newNode;在同一次推动之后:
head\n \xe2\x86\x93\n111 \xe2\x86\x92 222 \xe2\x86\x92 333\n \xe2\x86\x91\n tail\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1503 次 |
| 最近记录: |