Home > Software engineering >  Linked List issue when inserting a new item in Javascript
Linked List issue when inserting a new item in Javascript

Time:12-05

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?

CodePudding user response:

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)

CodePudding user response:

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)

  • Related