2017-12-29 47 views
3

jsで循環リンクリストを作成したいと思います。私はクロームでこのコードを実行すると、私は接続で何もしてクロム滞在を見ないプロトタイプの循環リンクリストとオブジェクトプロパティの変更時のエラー

var dll = new CircularLinkedList(); 
dll.push('a',2); 
dll.push('b',3); 

var node = { // make node 
    name: '', 
    score: '', 
    next: null, 
    previous: null 
} 

function CircularLinkedList(){ // Circular Linked List constructor 
    this.head = null; 
} 

CircularLinkedList.prototype.push = function(name , score){ 
    var head = this.head, 
    current = head, 
    previous = head, 
    node = {name: name, score: score, previous:null, next:null }; 


if(!head){ // if link list was empty 
    node.previous = node; 
    node.next = node; 
    this.head = node;  // ****the problem is here**** line 18 
} 
else{ 
    while(current && current.next){ // find last element in link list 
     previous = current; 
     current = current.next; 
    } 

    node.next = head; 
    node.previous = current; 
    head.previous = node; 
    current.next = node; 
    } 
} 

そして、私が書くのメインファイルに:私はこれを行います。例えば 私は

this.head = "s" 

にコードに問題がない持っているライン18を(****問題は****ここにある)を変更する場合。私は何をすべきか?円形で

答えて

1

新しいアイテムたちは頭を取得する方法スニペット

+0

として更新

var CircularList = function(){ this.push = function (value) { var newNode = { value: value }; if (this.head) { newNode.next = this.head; newNode.previous = this.head.previous; this.head.previous.next = newNode; this.head.previous = newNode; } else { this.head = newNode; newNode.next = newNode; newNode.previous = newNode; } }; } var cl = new CircularList(); cl.push({name: "hello"}); cl.push({name: "good"}); cl.push({name: "sir"}); document.body.innerText = cl.head.value.name + " " + cl.head.next.value.name \t + " " + cl.head.previous.value.name;

を押すと、リストを横断する必要はありません?私は使用できません 'myVar.head'はnullを返します –

+0

@MohammadJavadAbbasi https://jsfiddle.net/ys1r7yzs/ –

+0

ありがとうございます。私は頭を得ることができないアヤックスを使いました。私の問題は解決した:) –

関連する問題