Insert A Node At The End of Doubly Linked List (JS)

Hello Coders! Welcome to nkcoderz website. In this post, you will learn how to insert new node at the end of the Doubly Linked List js, Code for the above task given below:

Insert A Node At The End of Doubly Linked List (JS)

class Node
{
    constructor(val)
     {
            this.data = val;
            this.prev = null;
            this.next = null;
     }
}
var head = null;
function insertlast(val)
{
      var last = new Node(val);

      if(head == null)
      {
          last.prev = null;
          last.next = null;
          head = last;
      }
      else
      {
          var temp = head;
          while(temp.next != null)
          {
             temp = temp.next;
          }

          temp.next = last;
          last.prev = temp;
          last.next = null;
      }
}
function print()
{
      var temp = head;
      var last = null;
      
      while(temp != null)
      {
          document.write(temp.data);
          if(temp.next == null)
              last = temp;
          temp = temp.next;
      }
}
insertlast(10);
insertlast(20);
insertlast(30);

print();

In the above code, we are doing following things:

Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment