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:
- 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 two functions, print and insertfirst to look code neat and consize.
- In insertfirst we are using variable first as new node
- First check if doubly linked list in empty then make the first node as head
- Else make the first node points to head make the first node as head.
- This is how we accomplish the task.