Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Adding Last Node to a Linked List

I am learning how to add node to the linked list. The following is the correct code:

class NodeList {
    constructor(head = null){
        this.head = head 
        this.addLast = function (data) {
            
            let node = new Node(data)
            console.log(curr)
        
            if (this.head === null) {
                return this.head = node
            } else{
                let curr = this.head
                while(curr.next){
                    curr = curr.next
                }
                curr.next = node
               
            }
        }
    }
}

Initially,

i wrote the code as such:

class NodeList {
    constructor(head = null){
        this.head = head 
        this.addLast = function (data) {

            let node = new Node(data)
            console.log(curr)

            if (this.head === null) {
                return this.head = node
            } else{
                let curr = this.head
                while(curr.next){
                    curr = curr.next
                }
                curr.next = node

            }
        }
    }
}

The main difference is at the if statement. Instead of

if(this.head === null) { return this.head = node} 

I wrote

let curr = this.head

if(curr  === null) { return curr  = node}

However, the code doesn't work.

If I do something like

let nodeList = new Nodelist nodeList.addLast(2)

I expect to get head: Node {data: 2, next: null}. The first code achieved that purchase but the second code does not. I am confused why this is so. Both codes look the same. Can someone enlighten me?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!