Open In App

JavaScript Program for Sum of Number Digits in a Linked List

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are going to write a JavaScript program on how to find the sum of number digits stored in a linked list. We are going to use the Iterative and Recursive techniques to find the Sum of number digits. A linked list is a data structure where elements are stored in nodes and each node points to the next node in the sequence.

Iterative Method

In this approach, we will traverse through each node of the linked list using a loop to extract the digits of the data and calculate their sum.

Example: The below code uses a loop to iterate through each element of the linked list and get the sum of them.

Javascript




class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 
function sumOfDigitsIterative(head) {
    let sum = 0;
    while (head != null) {
        sum += head.data;
        head = head.next;
    }
    return sum;
}
 
const head = new Node(15);
head.next = new Node(-20);
head.next.next = new Node(35);
 
console.log(`Total Sum: ${sumOfDigitsIterative(head)}`);


Output

Total Sum: 30

Recursive Method

In this approach, we will create a recursive function which calls itself to traverse the linked list and calculate the sum of digits.

Example: The below code uses the recursion method to iterate and get the sum of each element in the linked list.

Javascript




class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 
function sumOfDigitsRecursive(head) {
    if (head == null) {
        return 0;
    }
    const restSum = sumOfDigitsRecursive(head.next);
    return head.data + restSum;
}
 
const head = new Node(-12);
head.next = new Node(13);
head.next.next = new Node(15);
 
console.log(`Total Sum: ${sumOfDigitsRecursive(head)}`);


Output

Total Sum: 16


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads