单链表 JavaScript 实现。 它对头返回 true,但所有其他节点返回 false。 为什么 contains 方法返回 false? 我认为我添加的 toTail 函数会出现问题。 但是当我打印链接列表时,它给了我所有节点
"use strict";
var LinkedList = function(){
this.head = null
}
var node = function(value){
this.value = value;
this.next = null;
}
LinkedList.prototype.addToHead = function(value){
var n = new node(value);
if(!this.head){
this.head = n;
}else{
this.next = this.head;
this.head = n;
}
};
LinkedList.prototype.addToTail = function(value){
var cur = null;
var n = new node(value)
if(!this.head){
this.head = n;
}else{
cur = this.head;
while(cur.next){
cur = cur.next;
}
cur.next = n;
}
}
LinkedList.prototype.contains = function(value) {
var node = this.head;
while (node) {
if (node.value === value) {
return true;
}
node = node.next;
}
return false;
};
var ll = new LinkedList();
ll.addToTail(20)
ll.addToTail(40)
ll.addToHead(8)
console.log(ll.contains(40))
最佳答案
我认为问题出在你的 addToHead 函数中。目前,如果头已存在,您将丢失列表:
"use strict";
var LinkedList = function(){
this.head = null
}
var node = function(value){
this.value = value;
this.next = null;
}
LinkedList.prototype.addToHead = function(value){
var n = new node(value);
if(!this.head){
this.head = n;
}else{
// this.next = this.head; <- What you had
n.next = this.head; // What it should be
this.head = n;
}
};
LinkedList.prototype.addToTail = function(value){
var cur = null;
var n = new node(value)
if(!this.head){
this.head = n;
}else{
cur = this.head;
while(cur.next){
cur = cur.next;
}
cur.next = n;
}
}
LinkedList.prototype.contains = function(value) {
var node = this.head;
while (node) {
if (node.value === value) {
return true;
}
node = node.next;
}
return false;
};
var ll = new LinkedList();
ll.addToTail(20)
ll.addToTail(40)
ll.addToHead(8)
console.log(ll.contains(40))
关于javascript - 链表包含函数返回 false,为什么? JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646068/