How to use Array’s Reduce Method In Javascript
This approach involves converting the linked list to an array and then using the reduce method to calculate the sum. This method leverages JavaScript’s array functionalities for a concise solution.
Example: The example usage demonstrates creating a linked list, converting it to an array, and then finding the sum of its elements using the reduce method.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
add(data) {
let new_node = new Node(data);
new_node.next = this.head;
this.head = new_node;
}
toArray() {
let arr = [];
let curr = this.head;
while (curr !== null) {
arr.push(curr.data);
curr = curr.next;
}
return arr;
}
}
function sum(list) {
return list.toArray().reduce((acc, val) => acc + val, 0);
}
let list = new LinkedList();
list.add(4);
list.add(6);
list.add(2);
list.add(5);
let total = sum(list);
console.log("Sum of numbers using reduce: " + total);
Output
Sum of numbers using reduce: 17
Time Complexity: O(n)
Space Complexity: O(n), due to the additional space required for the array.
JavaScript Program to Find Sum of Elements in Linked List
We are given a linked list, we have to find the sum of all the elements of that linked list. A linked list is a data structure to store data where each piece of information is connected to the next one, forming a chain. Each piece has its data and knows where to find the next piece. It’s a basic but useful method to organize and manage data.
There are several approaches to finding the sum of the elements in a linked list using JavaScript which are as follows:
Table of Content
- Using While Loop
- Using Recursive Approach
- Using Array’s Reduce Method