Length of Linked list in javascript
2 min readJan 2, 2021
There are two ways to find length of linked list —
- Simple - Looping through complete linked list till
next=null
- 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());