I am looking to create a circular linked list in JavaScript. Here is my code:
var node = { // creating a node
name: '',
score: '',
next: null,
previous: null
}
function CircularLinkedList(){ // Constructor for Circular Linked List
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 the linked list is empty
node.previous = node;
node.next = node;
this.head = node; // ****the issue lies here**** line 18
}
else{
while(current && current.next){ // finding the last element in the linked list
previous = current;
current = current.next;
}
node.next = head;
node.previous = current;
head.previous = node;
current.next = node;
}
}
In my main file, I have the following code:
var dll = new CircularLinkedList();
dll.push('a',2);
dll.push('b',3);
When I run this code in Chrome, nothing appears and Chrome remains stuck on connecting. However, if I change line 18 (****the issue lies here****) to
this.head = "s"
The code runs without any issues. Can you suggest a solution?