techStackGuru

Find Length of Linked Lists


linked-list-1

Iterative Solution

function getLength() {
  let count = 0;
  let temp = head;
      
  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;
 }
}

let head;
  
// Inserts a new Node 
function add(new_data) {
      
  let add_node = new Node(new_data);
    
  // Make next Node as head
  add_node.next = head;
    
  // Point to new Node
  head = add_node;
}
    
add(1);
add(2);
add(3);

function getLength() {
  let count = 0;
  let temp = head;
      
  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;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

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

    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }

  }

  getCount() {
    let current = this.head;
    let count = 0;

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

    return count;
  }
}


const node = new LinkedList();
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;
  }
}
class LinkedList {
 addNode(value) {
      let head = this.head;
      let node = new Node(value);
      if (head == null) {
          this.head = node;
      }
      else {
          while (head.next != null) {
              head = head.next;
          }
          head.next = node;
      }
  }
  getLength() {
      const length = (head) => {
          if (head == null) {
              return 0;
          }
          return 1 + length(head.next);
      }
      return length(this.head);
  }
}
const list = new LinkedList();
list.addNode(10);
list.addNode(20);
list.addNode(30);

console.log("length is :", list.getLength());  // length is : 3