The issue with updating a property in the prototype of a circular linked list

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?

Answer №1

When adding a new item to a circular list, there is no need to traverse the entire list.

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;

Displayed as code snippet

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a <SCRIPT> within an Ajax-loaded webpage

Utilizing Framework7 for my web application has been great since it allows me to load pages using Ajax, giving it an app-like feel. However, I am facing a challenge with making the "ad" code display properly on Ajax-loaded pages. If you inspect the ad co ...

I am currently grappling with a JavaScript mouse over event and encountering some difficulties

I am looking to dynamically change the background image of my body div whenever a link is hovered over. Here is a snippet of my code: JAVASCRIPT: var i = 0, anchors = document.querySelectorAll("zoom"), background = document.getElementById("body") ...

Painting issue on Chrome and Opera browsers

I've discovered a strange issue with my page rendering in blink browsers where it paints and then suddenly "unpaints." Once the page has loaded, most of the viewport becomes blank and stops painting. Here is how the screen should look after I manually ...

Button's focus event doesn't trigger on iPad

I am facing an issue with adding a bootstrap popover to my website. The popover should appear when the user clicks a button using the focus event. This functionality works fine on desktop browsers, but on the iPad, it seems like Safari on iOS does not trig ...

Search for the text using jQuery and then conceal it

I am attempting to conceal specific text within paragraphs, however, the issue is that the script identifies the entire paragraph and removes it completely. My goal is to only remove the text that has been identified. Check out the demo here <div cla ...

Utilizing Algolia search hits in conjunction with React Router: A guide

I'm currently utilizing Algolia’s react instant search feature, and I’m seeking guidance on how to implement a code snippet that will direct me to a designated page when a "hit" from the hits widget is clicked. My project is built using Next.js. ...

Switching between different sections of a webpage

Seeking assistance with implementing a transition effect between sections on a single-page application. All sections are located on the same page, but only one section is displayed at a time. When an event occurs, the display property of the requested sect ...

Utilize Ajax to invoke a function simultaneously with another Ajax call that includes preventDefault to submit the data

I am currently implementing two AJAX calls within my form. The first call is used to dynamically update the options in the second select element based on the value selected in the first select element. This call reaches out to a PHP page to process the dat ...

Techniques for eliminating text enclosed by double parentheses in javascript

I am currently working on extracting data from Wikipedia, but I am facing a challenge with removing content enclosed in multiple parentheses. While I can successfully remove single parentheses using content.replace(/\s*\(.*?\)\s*/g, &ap ...

Maintain checkbox selection even after the page is refreshed

Having trouble fetching all objects from the favorites array and setting the checkbox to checked. I've attempted using localStorage but the values are not saved after refreshing, despite researching online for solutions. Any assistance would be great ...

Assassin eradicated from list of cast members

In my quest to select a killer from the Cast Members Array for the game, I want the function to pick one person as the killer and then remove them from the castMember player array. Once the killer is chosen, they should be removed from the survivors array ...

AngularJS allows for submitting form data to a new window by utilizing the form

At the moment, I have a JavaScript function that sends a form POST request and opens it in a new window. Now, I want to convert this into AngularJS. Here's the current function. The three parameters passed in determine the post URL and some data valu ...

Ways to conceal #div element from displaying in the href attribute within the anchor tag

My anchor tag has an href attribute that looks like this: <a onclick='loadReview(\"" + strexternalURL + "\");' href='#productName1'. When clicking on it, the URL appears as http://localhost:54986/Dealerlist.aspx#productName ...

When attempting to load a JSON file, a Node.js loader error is triggered stating "Error: Cannot find module 'example.json'" while running transpiled code through Babel

When it comes to importing or requiring JSON (.json) files in TypeScript code, there have been multiple questions addressing similar issues. However, my query specifically pertains to requiring a JSON file within an ES6 module that is transpiled to the cur ...

Ways to display multiple select options based on the user's selection of multiple choices and ensure they remain hidden and reset when deselected with the use of

There is a select options field that contains languages, where the user can choose multiple language options or just one. When the user selects a language, a new select option should appear for them to choose their proficiency level in that language. If t ...

There appears to be an issue with the functionality of the JavaScript calculation function

Check out this JS Fiddle. I've tried my best in writing the script, but it just doesn't seem to work properly. If you could spare some time to review it and provide feedback on what I might be missing or doing wrong, I would greatly appreciate it ...

Issue with Puppeteer in Node.js causing if/else statements to not work as expected

const found = await page.waitForSelector('[name="commit"]'); if (found) { await page.click('[name="commit"]'); console.log('Clicked successfully'); } else { await browser.close(); console.log('Selector not ...

Creating space between flex items in Slick Carousel with Vue

This is my current Slick Carousel. There are 4 items in a row, and I am looking to insert some margin between each item while maintaining the existing aspect-ratio: 1.3/1; I'm struggling with overriding the classes from vue-slick-carousel. Does any ...

What could be the reason for JSON refusing to accept an element from an array?

I am looking to retrieve the exchange rates for all currencies from an API using an array that lists all available currencies. Below is the JavaScript code I have written: var requestURL = 'https://api.fixer.io/latest'; var requestUrlstandard ...

How come certain rectangles vanish when one rectangle completely fills the space?

Currently, I am encountering an issue with CSS paint worklet and I am trying to determine if it's a browser bug or an error on my end. In the worklet, I am drawing multiple rectangles. Strangely, when one rectangle covers the entire area, the others s ...