这是我到目前为止编写的代码。我认为在“Node”函数中使用循环不一定走在正确的轨道上......
function LinkedList() {
this.head = null;
this.tail = null;
this.length = 0;
}
function Node(...val) {
if (Array.isArray(val)) {
for (let i = 0; i < val.length; i++) {
this.push(val[i])
}
}
this.value = val;
this.next = null;
}
LinkedList.prototype.push = function(val) {
let newNode = new Node(val);
if(!this.head) {
this.head = newNode;
return this.head;
}
let tail = this.head;
while (tail.next !== null) {
tail = tail.next;
}
tail.next = newNode;
return this.head;
};
这是我尝试在其上运行的测试...
const newList = new LinkedList(5, 1, 2, 6, 8);
console.log(newList.head.value);
console.log(newList.head.next.value);
console.log(newList.head.next.next.value);
console.log(newList.head.next.next.next.value);
console.log(newList.head.next.next.next.next.value);
console.log(newList.head.next.next.next.next.next);
控制台日志的输出只是“无法读取 null 的属性(读取“值”)。
有人可以指出我做错了什么或下一步该去哪里吗?感谢您的宝贵时间!
最佳答案
问题是你的LinkedList
构造函数没有任何参数,因此当您使用 new LinkedList(5, 1, 2, 6, 8);
构造它时这些参数将被忽略。
您可能放错了参数处理的位置,并将其放在Node
中构造函数,而它应该位于 LinkedList
中构造函数。
所以移动该代码和参数定义,它就会起作用。
其他一些需要改进的地方:
没有必要执行
Array.isArray
检查,自...val
当函数被调用时,参数声明总是给你一个数组——当没有传递参数时它的长度可能为0,但它仍然是一个数组。push
方法不应该经过循环。您已经拥有tail
引用,所以使用它。push
方法应该更新length
属性(property)——因为你拥有它。push
方法不应该返回任何内容。修改是在LinkedList
中完成的实例,并且调用者实际上不必知道Node
创建的实例。
这是工作版本:
function LinkedList(...val) {
this.head = null;
this.tail = null;
this.length = 0;
for (let i = 0; i < val.length; i++) {
this.push(val[i]);
}
}
function Node(val) {
this.value = val;
this.next = null;
}
LinkedList.prototype.push = function(val) {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
} else {
this.tail.next = newNode;
}
this.tail = newNode;
this.length++;
};
const newList = new LinkedList(5, 1, 2, 6, 8);
console.log(newList.head.value);
console.log(newList.head.next.value);
console.log(newList.head.next.next.value);
console.log(newList.head.next.next.next.value);
console.log(newList.head.next.next.next.next.value);
console.log(newList.head.next.next.next.next.next);
现代化
由于您的代码使用扩展语法,因此您没有理由不使用 class
语法,以及 for..of
循环。
为了避免调用者必须知道 Node
实例,使您的 LinkedList
使用 Symbol.iterator
进行迭代的类:
class LinkedList {
constructor(...values) {
this.head = null;
this.tail = null;
this.length = 0;
for (let value of values) {
this.push(value);
}
}
push(val) {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
} else {
this.tail.next = newNode;
}
this.tail = newNode;
this.length++;
}
*[Symbol.iterator]() {
let node = this.head;
while (node) {
yield node.value;
node = node.next;
}
}
}
class Node {
constructor(val) {
this.value = val;
this.next = null;
}
}
const newList = new LinkedList(5, 1, 2, 6, 8);
for (let value of newList) {
console.log(value);
}
关于javascript - 尝试创建一个 Node 类函数,它接受一个项目数组并将它们全部推送到一个链接列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70382666/