我想使用 Javascript 打印所有链接列表项。在这里我为此创建了 Node 类。但我的 printlist() 方法打印未定义。有人可以帮助我吗?
这是我的代码:
class Node {
constructor(data) {
this.data = data;
this.next = null;
this.head = null;
}
setNextNode(node) {
this.next = node;
}
getNextNode() {
return this.next;
}
printlist() {
let newhead = this.head;
let output = " ";
while (newhead !== null) {
output += newhead.data + ' ';
console.log(output);
newhead = newhead.getNextNode(this.next);
}
}
}
const n1 = new Node(1);
const n2 = new Node(2);
const n3 = new Node(3);
n1.next = n2;
n2.next = n3;
//console.log(n1);
console.log(n1.printlist());
在构造函数中,您应该为 this.head 设置一个值(类似于 this 或 this.next)。
class Node {
constructor(data) {
this.data = data;
this.next = null;
this.head = this;
}
setNextNode(node) {
this.next = node;
}
getNextNode() {
return this.next;
}
printlist() {
let newhead = this.head;
let output = " ";
while (newhead !== null) {
output += newhead.data + ' ';
console.log(output);
newhead = newhead.getNextNode(this.next);
}
}
}
const n1 = new Node(1);
const n2 = new Node(2);
const n3 = new Node(3);
n1.next = n2;
n2.next = n3;
//console.log(n1);
console.log(n1.printlist());
问题是你的节点的
head
引用是null
,所以printList
中的循环不会循环。
head这个概念不属于Node类,而是属于容器类。它是对 first 节点的引用,因此它不应该是每个节点的属性。
我也不会有
printList
方法,但要使列表可迭代。这样它就变得更加灵活,并且对于调用者来说打印变得非常容易。
具体操作方法如下:
class Node {
constructor(data, next=null) { // Allow optional argument
this.data = data;
this.next = next;
// No head property here
}
}
class LinkedList {
constructor() {
this.head = null; // Here we want a head reference
}
prepend(data) {
this.head = new Node(data, this.head);
}
*[Symbol.iterator]() { // Make a list iterable
let node = this.head;
while (node) {
yield node.data;
node = node.next;
}
}
}
const list = new LinkedList();
list.prepend(3);
list.prepend(2);
list.prepend(1);
console.log(...list); // This will call the iterator method