这里我有两个类,Node 类和 LinkedList 类。我想知道为什么我可以在 LinkedList 类中使用 Node 类中的方法。
例如,在 LinkedList 类中的 .addToTail() 方法中,我对初始化为“this.head”的尾部变量使用了 .setNextNode() 和 .getNextNode() 方法。由于“this.head”不是Node类的实例,所以它应该无法使用Node类中的方法,对吧......?还是我遗漏了什么?
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
getNextNode() {
return this.next;
}
setNextNode(node) {
if (node instanceof Node || node === null) {
this.next = node;
} else {
throw new Error('Error!');
}
}
}
class LinkedList {
constructor() {
this.head = null;
}
addToHead(data) {
let newHead = new Node(data);
let currentHead = this.head;
this.head = newHead;
if (currentHead) {
this.head.setNextNode(currentHead);
}
}
addToTail(data) {
let tail = this.head;
if (!tail) {
this.head = new Node(data);
} else {
while(tail.getNextNode()) {
tail = tail.getNextNode()
}
tail.setNextNode(new Node(data));
}
}
}