Creating a Doubly Linked List using Javascript


Lets start by defining a simple class with a constructor that initializes the head and tail to null. We'll also define another structure on the prototype of the DoublyLinkedList class that'll represent each node in the linked list. 

Example

class LinkedList {
   constructor() {
      this.head = null;
      this.tail = null;
      this.length = 0;
   }
}
LinkedList.prototype.Node = class {
   constructor(data) {
      this.data = data;
      this.next = null;
      this.prev = null;
   }
};

Let's also create a display function that'll help us see how our list looks like. This function works as follows.

  • It starts from the head.
  • It iterates over the list using currElem = currElem.next till currElem doesn't become null, ie, we've not reached the end.
  • It prints data for each of the iterations.

Here is an illustration for the same −

Now let's have a look at how we'll implement this − 

Example

display() {
   let currNode = this.head;
   while (currNode != null) {
      console.log(currNode.data + " -> ");
      currNode = currNode.next;
   }
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 15-Jun-2020

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements