In previous post, we learnt how to create a linked list in js, now in this post, we will learn how to insert node at beginning of linked list in javascript.
Insert A Node At The Beginning Of Linked List In JavaScript
class Node
{
constructor(val)
{
this.data = val;
this.next = null;
}
}
var head = null;
function insertfirst(val)
{
var first = new Node(val);
first.next = head;
head = first;
}
function print()
{
var temp = head;
while(temp != null)
{
document.write(temp.data);
temp = temp.next;
}
}
insertfirst(5);
insertfirst(10);
insertfirst(15);
insertfirst(20);
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
- And assigning the value and then pointing it to head
- Making the new head to first.
- After this we are making the New node head.
The Output will be:
20
15
10
5