它发生错误,如TypeError: Cannot read property 'element' of null
我用这样的JavaScript编写LinkedList代码,我定义了两个方法insert
和find
,但这在find TypeError: Cannot read property 'element' of null
中出现错误
function Node(element) {
this.element = element;
this.next = null;
}
function LList() {
this.head = new Node("head");
this.find = find;
this.insert = insert;
}
function insert(newElement, item) {
var newNode = new Node(newElement);
var current = this.find(item);
newNode.next = current.next;
current.next = newNode;
}
function find(item) {
let currNode = this.head;
while (currNode.element != item) {
currNode = currNode.next;
}
return currNode;
}
var cities = new LList();
cities.insert("Conway", "head");
cities.insert("Rust", "Conway");
cities.find("Rust");
cities.display();
我看到currNode
是null
,但我确实给了currNode值。