单链表javascript实现。
它对头部返回true,但所有其他节点返回false。
为什么包含方法返回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))

09-25 18:36
查看更多