educative.io

Educative

Javascript - simple linked list traversal issue

Hi All,

I have implemented a single linked list using javascript. Please find the code below:

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

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

  isEmpty() {
    return this.head === null;
  }

  insertAtHead(data) {
    const tempNode = new Node(data);
    tempNode.nextElement = this.head;
    this.head = tempNode;
  }

  traverse() {
    let current = this.head;
    while (current.nextElement != null) {
      console.log("node data", current.data);
      current = current.nextElement;
    }
  }

  insertAtTail(data) {
    const tempNode = new Node(data);
    if (this.head === null) {
      this.head = tempNode;
      return;
    }

    let currentNode = this.head;
    while (currentNode.nextElement != null) {
      currentNode = currentNode.nextElement;
    }

    currentNode.nextElement = tempNode;
  }
}

const linkedList = new LinkedList();
linkedList.insertAtTail(12);
linkedList.insertAtTail(23);
linkedList.insertAtTail(25);

linkedList.traverse();

But the traverse method never prints the last element. What am i missing here ? Can anybody please help me out here ?
thx

Hey @ashwin3

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

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

  isEmpty() {
    return this.head === null;
  }

  insertAtHead(data) {
    const tempNode = new Node(data);
    tempNode.nextElement = this.head;
    this.head = tempNode;
  }

  traverse() {
    let current = this.head;
    while (current != null) {
      console.log("node data", current.data);
      current = current.nextElement;
    }
  }

  insertAtTail(data) {
    const tempNode = new Node(data);
    if (this.head === null) {
      this.head = tempNode;
      return;
    }

    let currentNode = this.head;
    while (currentNode.nextElement != null) {
      currentNode = currentNode.nextElement;
    }

    currentNode.nextElement = tempNode;
  }
}

const linkedList = new LinkedList();
linkedList.insertAtTail(12);
linkedList.insertAtTail(23);
linkedList.insertAtTail(25);

linkedList.traverse();

We have corrected your code. In traverse() you were checking for current.next element to be null but instead, we have to check only the current element whether it’s null or not, so when the current element reaches null we have to stop there and print the list.

Happy learning,