# Find Length of Linked Lists

## Iterative Solution

``````function getLength() {
let count = 0;

while (temp != null) {
count++;
temp = temp.next;
}
return count;
} ``````

## Recursively Solution

``````function getLength() {
const count = (data) => {
if (data == null) {
return 0;
}
return 1 + count(data.next);
}
return count(this.root);
}``````

## Example (Iterative)

``````class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}

// Inserts a new Node

// Make next Node as head

// Point to new Node
}

function getLength() {
let count = 0;

while (temp != null) {
count++;
temp = temp.next;
}
return count;
}

console.log('Length is :', getLength()) // Length is : 3``````

## Example 2 (Iterative)

In this example, the linked list is expanded by using the push method, and the lists length is calculated by using the getCount method.

``````class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}

constructor() {
this.tail = null;
}

push(value) {
const newNode = new Node(value);

this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}

}

getCount() {
let count = 0;

while (current) {
count++;
current = current.next;
}

return count;
}
}

node.push(10);
node.push(20);
node.push(30);
node.push(40);
node.push(50);

console.log(node.getCount()); // Output: 5 ``````

## Example (Recursively)

``````class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
let node = new Node(value);
}
else {
}
}
}
getLength() {
const length = (head) => {
return 0;
}