w3resource

JavaScript Exercises: Count number of nodes in a Singly Linked List

JavaScript Singly Linked List: Exercise-3 with Solution

Write a JavaScript program to create a singly linked list of n nodes and count the number of nodes.

Sample Solution:

JavaScript Code:

// Define a class representing a node in a singly linked list
class Node {
    constructor(data) {
        // Initialize the node with provided data
        this.data = data
        // Initialize the next pointer to null
        this.next = null                
    }
}

// Define a class representing a singly linked list
class SinglyLinkedList {
    constructor(Head = null) {
        // Initialize the head of the list
        this.Head = Head
    }

    // Method to add a new node to the end of the list
    add(newNode){
        // Start traversal from the head node
        let node = this.Head;
        // If the list is empty, set the new node as the head and return
        if(node == null){
            this.Head = newNode;
            return;
        }
        // Traverse the list until the last node
        while (node.next) {
            node = node.next;
        }
        // Set the next pointer of the last node to the new node
        node.next = newNode;
    }

    // Method to count the number of nodes in the list
    NodeCount() {
        // Initialize a counter variable
        let ctr = 0;
        // Start traversal from the head node
        let node = this.Head;
        // Traverse the list and increment the counter for each node
        while (node) {
            ctr++;
            node = node.next;
        }
        // Return the total count of nodes
        return ctr;
    } 

    // Method to display the elements of the list
    displayList(){
        // Start traversal from the head node
        let node = this.Head;
        // Initialize an empty string to store the elements of the list
        var str = ""
        // Traverse the list and concatenate each element to the string
        while (node) {
            str += node.data + "->";
            node = node.next;
        }
        // Append "NULL" to indicate the end of the list
        str += "NULL"
        // Print the string containing the list elements
        console.log(str);  
    } 
}

// Create an instance of the SinglyLinkedList class
let numList = new SinglyLinkedList();
// Add nodes with data values to the list
numList.add(new Node(2));
numList.add(new Node(3));
numList.add(new Node(4));
numList.add(new Node(5));
numList.add(new Node(6));
numList.add(new Node(7));
// Display the original elements of the list
console.log("Original Linked list:")
numList.displayList();
// Count the number of nodes in the list
var ctr = numList.NodeCount();
// Display the number of nodes in the list
console.log("Number of elements in the said Linked list: "+ctr)

Output:

Original Linked list:
2->3->4->5->6->7->NULL
Number of elements in the said Linked list: 6

Flowchart:

Flowchart: JavaScript Exercises: Count number of nodes in a Singly Linked List.

Live Demo:

See the Pen javascript-singly-linked-list-exercise-3 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Singly Linked List Previous: Print a singly linked list in reverse order.
Singly Linked List Next: Insert a new node at any position of a Singly Linked List.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/linkedlist/javascript-singly-linked-list-exercise-3.php