Insert A Node At Beginning of Circular Linked List (JS)

In previous post, we disussed about creating a cirular linked list, but we have not discussed how to insert a node? In this post we will learn how to insert a node at beginning of circular linked list js.

Insert A Node At Beginning of Circular Linked List (JS)

class Node
{
    constructor(val)
     {
            this.data = val;
            this.next = null;
      }
}
var head = null;
function insertfirst(val)
{
      var first = new Node(val);
      if(head == null)
      {
          first.next = first;
          head = first;
      }
      else
      {
           var last = head;
           while(last.next != head)
           {
               last = last.next;
           }
           last.next = first;
           first.next = head;
           head = first;
      }
}
function print()
{
    var temp = head;
    do
    {
        document.write(temp.data);
        temp = temp.next;
    }while(temp != head);
}
insertfirst(10);
insertfirst(20);
insertfirst(30);

print();

In the above code we have:

In insertfirst function we are creating new node named first , checking if head is null then point the first node to itself and make itself as head.

Else we are traversing till end and linking it with the first node and first’s next to head. Making the first as head.

Then printing using do while loop until temp is not equal to head.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment