Delete A Node In A Doubly Linked List (JS)

Hello Coders! Welcome to nkcoderz website. In this post, you will learn how to delete a node in a doubly linked list js, code for the above task given below:

How To Delete A Node In A 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 del(key)
{
     if(head == null)
          return;

      var temp = head;
      while(temp != null && temp.data != key)
      {
          temp = temp.next;
      }
      if(temp == null)
          document.write("Key Not Found");
      else if(temp == head)
      {
          head = head.next;
          head.prev = null;
      }
      else if(temp.next == null)
          temp.prev.next = null;
      else
      {
          temp.prev.next = temp.next;
          temp.next.prev = temp.prev;
      }
}
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(5);
insertlast(10);
insertlast(15);
print();
document.write("After deleting:")
del(10);
print();

In the above code we have:

Output:

5
10
15
After deleting:
5
15


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment