链接列表包含函数返回false,为什么?的JavaScript

时间:2017-01-14 02:03:01

标签: javascript data-structures linked-list

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

1 个答案:

答案 0 :(得分:3)

我认为问题出在你的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))
&#13;
&#13;
&#13;