我想使用Javascript打印所有的链表项。这里我为此创建Node类。但是我的printlist()方法打印的是undefined。有人能帮我吗?
这是我的代码:
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
不会循环。
头的概念不属于Node类,而是属于容器类。它是对第一个节点的引用,所以它不应该是每个节点的属性。
我也不会有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