JavaScript Program to Multiply all Numbers in the Linked List
Last Updated :
26 Feb, 2024
The JavaScript program aims to Multiply all numbers in the linked list. A linked list is a data structure consisting of a sequence of elements, where each element points to the next element in the sequence.
The program traverses the linked list and Multiply all numbers in the linked list.
Iterative Approach
In this approach, we will use a for loop to traverse the linked list and multiply each value stored in the linked list with each other.
Example: The below example implements the iterative approach to multiply numbers in a linked list in JavaScript.
Javascript
class Node {
constructor(value) {
this .value = value;
this .next = null ;
}
}
function createLinkedList(arr) {
if (arr.length === 0) {
return null ;
}
let head = new Node(arr[0]);
let current = head;
for (let i = 1; i < arr.length; i++) {
current.next = new Node(arr[i]);
current = current.next;
}
return { head };
}
function multiplyIterative(head) {
let current = head;
let multiply = 1;
while (current !== null ) {
multiply *= current.value;
current = current.next;
}
return multiply;
}
const linkedList =
createLinkedList([-1, 2, -3, 4, 5]);
console.log(multiplyIterative(linkedList.head));
|
Recursive Approach
Implement a recursive function to traverse the linked list and multiply each encountering element with the previously calculated value.
Example: The below example multiplies the numbers in a linked list in JavaScript using recursion.
Javascript
class Node {
constructor(value) {
this .value = value;
this .next = null ;
}
}
function createLinkedList(arr) {
if (arr.length === 0) {
return null ;
}
let head = new Node(arr[0]);
let current = head;
for (let i = 1; i < arr.length; i++) {
current.next = new Node(arr[i]);
current = current.next;
}
return { head };
}
function multiplyNumbersRecursive(node, multiply = 1) {
if (node === null ) {
return multiply;
}
multiply *= node.value;
return multiplyNumbersRecursive(node.next, multiply);
}
const linkedList =
createLinkedList([-1, 2, -3, 4, -5]);
console.log(multiplyNumbersRecursive(linkedList.head));
|
Share your thoughts in the comments
Please Login to comment...