Insert A Node In The Beginning Of Doubly Linked List (JS)

In previous post we teach you about how to create a doubly linked list in js, well in this post, we going to learn about insert a node in the beginning of doubly linked list js. Let’s learn about it.

Insert A Node In The Beginning Of Doubly Linked List (JS)

class Node
{
    constructor(val)
     {
            this.data = val;
            this.prev = null;
            this.next = null;
     }
}
var head = null;
function insertfirst(val)
{
      var first = new Node(val);
      if(head == null)
      {
          first.prev = null;
          first.next = null;
          head = first;
      }
      else
      {
          first.prev = null;
          first.next = head;
          head.prev = first;
          head = first;
    }
}
function print()
{
      var temp = head;
      var last = null;
      while(temp != null)
      {
          document.write(temp.data);
          if(temp.next == null)
              last = temp;
          temp = temp.next;
      }
}

insertfirst(5);
insertfirst(10);
insertfirst(15);

print();

In this program, we are doing following things:

  1. Creating a class Node and initialize the node object with constructor.
  2. Then we are initializing the data with given value and next as null.
  3. Initialize the head as NULL.
  4. Creating two functions, print and insertfirst to look code neat and consize.
  5. In insertfirst we are using variable first as new node
  6. First check if doubly linked list in empty then make the first node as head
  7. Else make the first node points to head make the first node as head.
  8. This is how we accomplish the task.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment