1

I have the next implementation of Linked List:

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

class LinkedLIst {
  constructor() {
    this.head = {};
  }

  add(head) {    
    if(!this.head.next) {
      this.head = new Node(head);
    }

    this.head.next = new Node(head);
  }
}


const list = new LinkedLIst();
list.add(1)
list.add(2)
list.add(3)


console.log(list)

I don't understand, why 2 is not added within the list? And how to fix that?

2 Answers 2

1

Since this is a linked list, I am assuming you want to insert at the end. To do that, you can create a tail property.

Then, in you add method, you can check if no elements exist, then set the head and tail to the new node. If there is at least 1 element, you can set the tail's next to the new node and finally, make the tail point to the new node.

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

class LinkedLIst {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  add(value) {    
    const newNode = new Node(value)
    if (this.head === null) {
      this.head = this.tail = newNode
    } else {
      this.tail.next = newNode
      this.tail = newNode;
    }
  }
}


const list = new LinkedLIst();
list.add(1)
list.add(2)
list.add(3)


console.log(list)

Sign up to request clarification or add additional context in comments.

5 Comments

could you please explain his statement ` this.tail.next = newNode this.tail = newNode;`?
Basically, your previous tail is going to be the second last element after you insert a new element. So, you are connecting the tail's next to the newNode. Once done, you want to update the tail again to point to the last node which is going to be the newNode
what is the purpose of tail?
As the name suggests, head tracks the first node of the linked list, and tail tracks the last node of the linked list.
could you explain please why my example does not work?
1

if you don't want to use tail just iterate until the end of the linklist

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

class LinkedLIst {
  constructor() {
    this.head = null;
  }

  add(head) {    
    
    if(!this.head) {
      this.head = new Node(head);
    }else{
      let ptr = this.head;    
      while(ptr.next!==null){
        ptr = ptr.next;
      }
      ptr.next=new Node(head);
    }
    
    
  }
}


const list = new LinkedLIst();
list.add(1)
list.add(2)
list.add(3)


console.log(list)

2 Comments

why do i need ptr variable, why i can not use this.head instead?
You need to because you alway want to add the latest node to the end of the list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.