Delete A Node In Linked List Using JavaScript

Are you looking for how to delete a node in linked list using javascript? If you are, then this is the right page, In this post you will quickly learn how to easily delete a node.

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

    if(head == null)
        head = last;
    else
    {
        var lastNode = head;

        while(lastNode.next != null)
        {
            lastNode = lastNode.next;
        }

        lastNode.next = last;
    }
}
function del(key)
{
    if(head.data == key)
    {
        head = head.next;
    }
    else
    {
        var temp = head;

        while(temp.next != null)
        {
            if(temp.next.data == key)
            {
                temp.next = temp.next.next;
                break;
            }
            else
                temp = temp.next;
        }
    }
}
function print()
{
    var temp = head;
    while(temp != null)
    {
        document.write(temp.data);
        temp = temp.next;
    }
}

insertlast(5);
insertlast(10);
insertlast(15);
insertlast(20);

print();
del(30);
document.write("After deleting")
print();

In the above code 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 three functions, print, delete and insertlast to look code neat and consize.
  5. In previous post, we have discussed about insertlast function, so you can read there.
  6. In del function we have used key.
  7. First it will check if head contains the key or not, if then make the new head to head’s next.
  8. Else traverse until last node
  9. Check the key if it is in next data then make the current node next points to next next node.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment