JavaScript Program to Find Sum of Elements in Linked List
Last Updated :
24 May, 2024
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:
Using While Loop
To find the sum of a linked list, we traverse each number in the list, adding them together. The function utilizes a while loop to iterate through each number in the linked list and find its sum. Starting with zero, the function adds the numbers one by one until it reaches the end of the list, providing the total sum of all numbers in the linked list.
Example: JavaScript program defining a linked list and populates it with values, and calculates the sum of its elements.
JavaScript
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;
}
}
function sum(list) {
let sum = 0;
let curr = list.head;
while (curr !== null) {
sum += curr.data;
curr = curr.next;
}
return sum;
}
let list = new LinkedList();
list.add(3);
list.add(8);
list.add(3);
list.add(1);
let total = sum(list);
console.log("Sum of numbers in the list: " + total);
OutputSum of numbers in the list: 15
Time Complexity: O(n)
Space Complexity: O(1)
Using Recursive Approach
The code features a recursive strategy to calculate the sum of linked list elements, showcasing a function that calls itself. Within the recursive function, node values are added, and the process continues until the end of the linked list is reached. This recursive approach simplifies the code, making it easy to sum, and linked list elements.
Example: The example usage illustrates the practical application of this recursive method, creating a linked list and utilizing the function to find the sum of its elements.
JavaScript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
add(data) {
let newNode = new Node(data);
newNode.next = this.head;
this.head = newNode;
}
}
function sum(node) {
if (node === null) {
return 0;
}
return node.data + sum(node.next);
}
let list = new LinkedList();
list.add(7);
list.add(3);
list.add(8);
list.add(2);
let total = sum(list.head);
console.log("Sum of numbers using recursion: " + total);
OutputSum of numbers using recursion: 20
Time Complexity: O(n)
Space Complexity: O(n), in this, and we are taking the stack space.
Using Array's Reduce Method
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.
JavaScript
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);
OutputSum of numbers using reduce: 17
Time Complexity: O(n)
Space Complexity: O(n), due to the additional space required for the array.
Similar Reads
JavaScript Program for Sum of Number Digits in a Linked List
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 ne
2 min read
JavaScript Program to Find Sum of Leaf Node in Binary Tree
Given a binary tree, We have to find the sum of all leaf nodes. A leaf node is a node that does not have any children. Example: Input binary tree: 1 / \ 2 3 / \ / \ 4 5 6 7The sum of leaf nodes would be: 4 + 5 + 6 + 7 = 22Table of Content Using recursive approachIterative Approach Using StackUsing r
3 min read
JavaScript Program to find Length of Linked List using JavaScript
Given a linked list, the task is to determine its length using various methods. The linked list is a fundamental data structure consisting of nodes connected in a chain, offering efficient data organization. Different approaches, including Iterative and Recursive Methods, enable us to compute the le
3 min read
JavaScript Program to Find Smallest Number in a Linked List
Given a linked list, the task is to find the smallest number in a linked list in JavaScript. 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 b
3 min read
Javascript Program To Find Decimal Equivalent Of Binary Linked List
Given a singly linked list of 0s and 1s find its decimal equivalent.Input: 0->0->0->1->1->0->0->1->0Output: 50 Input: 1->0->0Output: 4The decimal value of an empty linked list is considered as 0.Initialize the result as 0. Traverse the linked list and for each node, mul
3 min read
Javascript Program To Find The Sum Of Last N Nodes Of The Given Linked List
Given a linked list and a number n. Find the sum of the last n nodes of the linked list.Constraints: 0 <= n <= number of nodes in the linked list.Examples: Input : 10->6->8->4->12, n = 2 Output : 16 Sum of last two nodes: 12 + 4 = 16 Input : 15->7->9->5->16->14, n =
10 min read
Javascript Program For Inserting A Node In A Linked List
We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. JavaScript// Linked List Class // Head of list let head; // Node
7 min read
JavaScript Linked List Programs
JavaScript Linked List Programs contain a list of articles based on programming. Linked List is a linear data structure that stores data in linearly connected nodes. Linked lists store elements sequentially, but doesnât store the elements contiguously like an array. S. NoArticles1JavaScript Program
5 min read
Javascript Program For Finding Intersection Point Of Two Linked Lists
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. Above diagram shows an example with two linked lists havi
7 min read
Java Program to Search an Element in a Circular Linked List
A linked list is a kind of linear data structure where each node has a data part and an address part which points to the next node. A circular linked list is a type of linked list where the last node points to the first one, making a circle of nodes. Example: Input : CList = 6->5->4->3->
3 min read