javascript - 链表包含函数返回 false,为什么? JavaScript

标签 javascript data-structures linked-list

单链表 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/

相关文章:

javascript - 取消选中 angularjs 中的复选框

javascript - After Effects 中是否有一个编程/数学术语来说明 Linear() 函数的作用?

algorithm - 在矩阵中找到最大可访问节点

arrays - 吸引力作为编码

java - Java中的链表,如何将字符串数组转换为列表?

c++ - 在链表C++中搜索对象的某个字段

mysql - 在单个 Ruby/MySQL 查询中加载整个链表

javascript - 如何在javascript中添加字符串数值?

javascript - java.lang.NumberFormatException : For input string: "+i+"

c - 为什么我的程序每次运行时都会崩溃?