2017-01-14 2 views
0

単独リンクされたリストのJavaScriptの実装。 頭にはtrueを返しますが、他のすべてのノードはfalseを返します。 メソッドにfalseが返されるのはなぜですか? 私は間違ったことが私のtoTail機能を追加すると思う。 しかし、私はそれは私にすべてのノードリンクされたリストには、関数がfalseを返します。なぜですか? JavaScript

"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))

答えて

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))

関連する問題