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:
- Creating a class Node and initialize the node object with constructor.
- Then we are initializing the data with given value and next as null.
- Initialize the head as NULL.
- Creating three functions, print, delete and insertlast to look code neat and consize.
- In previous post, we have discussed about insertlast function, so you can read there.
- In del function we have used key.
- First it will check if head contains the key or not, if then make the new head to head’s next.
- Else traverse until last node
- Check the key if it is in next data then make the current node next points to next next node.