Length of Linked list in javascript

Ujjwal Gupta
2 min readJan 2, 2021

--

There are two ways to find length of linked list —

  1. Simple - Looping through complete linked list till next=null
  2. Recursively incrementing the length till reached last

In this article- i am going to explain both ways.

Simple- using loop

class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList { add(value) {
let root = this.root;
let node = new Node(value);
if (root == null) {
this.root = node;
} else {
while (root.next != null) {
root = root.next;
}
root.next = node;
}
}
length() {
let root = this.root;
let length = 0;
while (root != null) {
root = root.next;
++length;
}
return length;
}
}
const list = new LinkedList();
list.add(5);
list.add(51);
list.add(52);
console.log("length", list.length());

Recursively

class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList { add(value) {
let root = this.root;
let node = new Node(value);
if (root == null) {
this.root = node;
}
else {
while (root.next != null) {
root = root.next;
}
root.next = node;
}
}
lengthUsingRecursion() {
const length = (root) => {
if (root == null) {
return 0;
}
return 1 + length(root.next);
}
return length(this.root);
}
}
const list = new LinkedList();
list.add(5);
list.add(51);
list.add(52);
console.log("length by recursion", list.lengthUsingRecursion());

--

--

Ujjwal Gupta
Ujjwal Gupta

Written by Ujjwal Gupta

Building starscolab | Ex - Frontend lead Polygon | Creator of jsstore, fortjs | opensource creator | we3, blockchain, solidity | javascript

No responses yet