Create A Circular Linked List (JavaScript)

In this article, we will learn how to create a circular linked list (javascript), in previous post we discussed about doubly linked list.

Create A Circular Linked List (JavaScript)

class Node
{
     constructor(val)
     {
            this.data = val;
            this.next = null;
      }
}
var head = null;
var head = new Node(5);
var middle = new Node(10);
var last = new Node(15);

head.next = middle;
middle.next = last;
last.next = head;

var temp = head;
do
{
    document.write(temp.data);
    temp = temp.next;
}while(temp != head);

In Circular Linked List last node points to the head node instead of null, this make the list as circular.

In the above code, we are creating a singly linked list. In linking part, we are just pointing the last node to head node which makes it circular.

For printing we are using do while loop, this will print the data until temp becomes 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