Insert A Node In The End Of Circular Linked List (JS)

In this article, we learn about insert a node in the end of circular linked list js, so guys without wasting any time let’s know about it.

Insert A Node In The End Of Circular Linked List (JS)

class Node
{
    constructor(val)
     {
            this.data = val;
            this.next = null;
      }
}
var head = null;
function insertlast(val)
{
      var last = new Node(val);
      if(head == null)
      {
          last.next = last;
          head = last;
      }
      else
      {
          var temp = head;
          while(temp.next != head)
          {
              temp = temp.next;
          }

          temp.next = last;
          last.next = head;
      }
}
function print()
{
    var temp = head;
    do
    {
        document.write(temp.data);
        temp = temp.next;
    }while(temp != head);
}
insertlast(5);
insertlast(10);
insertlast(15);

print();

In the above code we have:

In insertlast function we have last as the new node. Now first check if head is null or not, if it is make the new node as head and it’s next point to itself.

Else go to the end node and link it with last node and make the last node next points to head.

Print using do while loop until temp not goes to head.

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

Leave a Comment