Create A Doubly Linked List In JavaScript

In previous posts, we have discussed about Singly Linked List. Now it’s time to move onto Doubly Linked List, But wait what is doubly linked list we will know about it in this post. Also we will know about how to create a doubly linked list in javascript.

What Is Doubly Linked List?

Doubly linked list is a linear data structure having nodes which contains two reference part, or two pointer and one data part. One pointer points to previous node and other points to the next node while the data remains in between them.

Advantage of Doubly Linked List

In doubly linked list we can traverse in both direction, unlike in the case of singly linked list where we can traverse only in one direction.

Create A Doubly Linked List In JavaScript

class Node
{
    constructor(val)
     {
            this.data = val;
            this.prev = null;
            this.next = null;
      }
}
var head = null;
var head = new Node(5);
var middle = new Node(10);
var last = new Node(15);

head.prev = null;
head.next = middle;
middle.prev = head;
middle.next = last;
last.prev = middle;
last.next = null;

var temp = head;
while(temp != null)
{
    document.write(temp.data);
    temp = temp.next;
}

In the above code, we have:

  1. Class for node, which containts two pointer prev and next and data.
  2. Initially the head is empty.
  3. Then we allocating the values.
  4. Connecting each node.
  5. Printing the node using traversing.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment