Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

110
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?

7 months ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.