find Length for singly Linked List - Node.js Data Structure

Node.js examples for Data Structure:List

Description

find Length for singly Linked List

Demo Code


function Node(value){
    this.value = value;/*  w  w  w .j  ava 2  s.  c om*/
    this.next = null;
}
function SLL(){
    this.head = null;
    this.length = 0;
}
SLL.prototype.add = (value) => {
    let node = new Node(value)
    let currentNode = this.head;
    if(!currentNode){
        this.head = node;
        this.length++;
        return node;
    } 
    while(currentNode.next){
        currentNode = currentNode.next;
    }
    currentNode.next = node;
    this.length++;
    return node;
}
SLL.prototype.findLength = () => {
    let currentNode = this.head;
    let count = 1;
    if(this.length === 0){
        return;
    }
    while(currentNode.next){
        currentNode = currentNode.next;
        count++;
    }
    return count;
}

var slist = new SLL();
slist.add(1)
slist.add(4)
slist.add(35)
slist.add(2)
slist.add(10)
slist.add(134)
slist.add(4)
slist.add(8);

console.log(slist.findLength());

Related Tutorials