Check if linked list is cyclic in javascript

Ujjwal Gupta
2 min readJan 3, 2021

A cyclic linked list is a special type of linked list which last node next points to root node.

So in order to check whether a linked list is cyclic or not, we need to traverse to last node & check whether it next is equal to root node.

Let’s write a method which will take a linked list and find out whether its cyclic or not —

function isCyclic(list) {
let current = list.root
while (current != null && current.next != null) {
if (current.next.data === list.root.data) {
return true;
}
current = current.next;
}
return false;
}

Now, let’s create a simple linked list, cyclic linked list & check for cyclic -

class Node {
constructor(value) {
this.data = value;
this.next = null;
}
}
class CyclicLinkedList {
add(value) {
let node = new Node(value);
let current = this.root;
if (current == null) {
this.root = node;
} else {
while (current.next != null && current.next.data != this.root.data) {
current = current.next;
}
node.next = this.root;
current.next = node;
}
}
}
class LinkedList {
add(value) {
const node = new Node(value);
let current = this.root;
if (current == null) {
this.root = node;
} else {
while (current.next != null) {
current = current.next;
}
current = current.next;
}
}
}
function isCyclic(list) {
let current = list.root
while (current != null && current.next != null) {
if (current.next.data === list.root.data) {
return true;
}
current = current.next;
}
return false;
}
const cylicList = new CyclicLinkedList();
cylicList.add(1);
cylicList.add(2);
cylicList.add(3);
const list = new LinkedList();
cylicList.add(1);
cylicList.add(2);
cylicList.add(3);
console.log("isCyclic", isCyclic(cylicList)); //true
console.log("isCyclic", isCyclic(list)); // false

--

--

Ujjwal Gupta

Frontend lead Polygon | Creator of jsstore, mahaljs | sqlweb, fortjs | opensource creator | we3, blockchain, solidity | javascript