如何解决JavaScript中带尾的LinkedList push方法
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++
}
具体来说,我不了解else
方法内的push()
部分。如果我们说next
,head
中的每个this.tail.next = newNode
都如何分配一个新节点?头尾之间的关系在哪里?如何说this.tail.next = newNode
,才能访问列表的head
属性?当我运行此代码时,它可以正确正确地工作,并且使我感到困惑。
const myList = new SinglyLinkedList();
myList.push("111");
myList.push("222");
myList.push("333");
console.log(myList);
输出:
SinglyLinkedList {
length: 3,head: Node { val: '111',next: Node { val: '222',next: [Node] } },tail: Node { val: '333',next: null } }
解决方法
如果我们说this.tail.next = newNode,
next
中的每个head
都将被分配一个新节点?头和尾之间的关系在哪里,通过说this.tail.next = newNode,我们如何访问列表的head属性?
让我们回到空白列表。第一次添加节点时,我们进入if
块,其中head
和tail
都将引用 same 新节点。这意味着从那一刻起,您在tail
中进行的任何更改都将对head
进行更改,因为它们引用的是同一对象。
现在执行第二个push
,我们进入else
块。在那里,我们将新节点分配给next
的{{1}}属性。但是由于这是tail
所指的同一对象,因此我们实际上在这里设置了head
!这仅发生在第二个head.next
上,因为在此分配之后,push
被分配了一个新的引用(tail
),因此从next
和head
开始指代不同的节点。
以图形方式:
在tail
之后:
push('111')
在head
↓
111
↑
tail
之后push('222')
之后:
this.tail.next = newNode;
...在同一次推送期间head
↓
111 → 222
↑
tail
之后:
this.tail = newNode;
在head
↓
111 → 222
↑
tail
之后push('333')
之后:
this.tail.next = newNode;
...在同一次推送期间head
↓
111 → 222 → 333
↑
tail
之后:
this.tail = newNode;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。