这是我迄今为止编写的代码。我不认为在"节点"函数中使用循环一定是正确的。。。
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的属性(读取"value"(。
有人能指出我做错了什么吗?或者下一步该去哪里?感谢您抽出时间!
问题是您的LinkedList
构造函数没有任何参数,因此当您使用new LinkedList(5, 1, 2, 6, 8);
构造它时,这些参数将被忽略。
您可能将参数处理放错了位置,并将其放在Node
构造函数中,而它本应放在LinkedList
构造函数中。
所以移动代码和参数定义,它就会工作。
其他需要改进的地方:
-
没有必要进行
Array.isArray
检查,因为...val
参数声明在调用函数时总是给您一个数组——当没有传递参数时,它的长度可能为0,但它仍然是一个数组。 -
push
方法不应该经过循环。你已经有一个tail
参考,所以使用它 -
push
方法应该更新length
属性——因为您有它。 -
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);
现代化
由于您的代码使用spread语法,因此没有理由不同时使用class
语法和for..of
循环。
为了避免调用者必须知道Node
实例,请使用Symbol.iterator
:使LinkedList
类可迭代
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);
}