Insert Node At Beginning Of Linked List In JavaScript

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:

  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 two functions, print and insertFirst to look code neat and consize.
  5. In insertfirst we are using variable first as new node
  6. And assigning the value and then pointing it to head
  7. Making the new head to first.
  8. After this we are making the New node head.

The Output will be:

20
15
10
5

Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment