【发布时间】:2022-12-09 21:58:14
【问题描述】:
在 Node 类中,next 的类型为 Node 或 null。通过这个我们只能将 Node 或 null 分配给 next
class Node {
value: any;
next: Node | null;
prev: Node | null;
constructor(value: any) {
this.value = value;
this.next = null;
this.prev = null;
}
}
但我在推送功能中看到,在这一行“this.tail!.next = newNode;”我们只将 newNode 引用分配给 next 属性,这里 newNode 只是一个引用,它不会像我们在 Node 类中那样具有值,或 next 或 prev 值。
push(value: any) {
const newNode = new Node(value);
if (this.length === 0) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail!.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
this.length++;
return this;
}
我真的无法理解,如何只给出一个类型为 Node 的 next 引用,而不是包含 value、next 和 prev 属性的 Node。
【问题讨论】:
-
在 typescript(和 javascript)中,引用和值之间没有区别,就像在 C++ 中一样。每个对象都通过引用访问。声明
aNode: Node与赋值aNode = new Node(...)完全兼容
标签: typescript data-structures linked-list nodes doubly-linked-list