循环链表和原型中更改对象属性时的错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了循环链表和原型中更改对象属性时的错误相关的知识,希望对你有一定的参考价值。

我想在js中制作循环链表。我这样做:

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;
    }
}

在主文件中我写道:

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

当我在chrome中运行此代码时,我看不到任何内容,并且chrome保持连接状态。例如,如果我将第18行(****问题在这里****)更改为

this.head = "s"

代码没有问题。我该怎么办?

答案

在循环中,您不需要在推送新项目时遍历列表

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	+ " " + cl.head.previous.value.name;

以上是关于循环链表和原型中更改对象属性时的错误的主要内容,如果未能解决你的问题,请参考以下文章

循环链表和双向链表

循环链表和双向链表

循环链表基础

双链表和循环链表

Java集合 -- ListSetMap三者的区别Arraylist 与 LinkedList 区别RandomAccess接口双向链表和双向循环链表ArrayList 与 Vector

循环链表