Search code examples
javascriptpropertieslinked-listprototype

circular linked list and error in changing objects property in prototype


I want to make circular linked list in js. I do this:

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

And in main file I write:

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

When I run this code in chrome, I see nothing and chrome stay in connecting. for example if I change line 18 (****the problem is here****) to

this.head = "s"

The code hasn't problem. what should I do?


Solution

  • In circular you don't need to traverse the list when pushing a new item

    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;

    Updated as snippet