This JavaScript program aims to print negative numbers present in a 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 prints all the negative numbers encountered.
Table of Content
Iterative Approach
The elements of the linked list are traversed using a loop and each one of them is checked for the negative value. It prints the negative values on the console.
Example: The below example prints negative numbers in a linked list in 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 printNegativeNumbersIterative(head) {
let current = head;
while (current !== null ) {
if (current.value < 0) {
console.log(current.value);
}
current = current.next;
}
} const linkedList = createLinkedList([-1, 2, -3, 4, -5]);
printNegativeNumbersIterative(linkedList.head); |
-1 -3 -5
Recursive Approach
Implement a recursive function to traverse the linked list, checking each element recursively and printing the negative numbers encountered.
Example: The below example is to print negative numbers in a linked list in 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 printNegativeNumbersRecursive(node) {
if (node === null ) {
return ;
}
if (node.value < 0) {
console.log(node.value);
}
printNegativeNumbersRecursive(node.next);
} const linkedList = createLinkedList([-1, 2, -3, 4, -5]);
printNegativeNumbersRecursive(linkedList.head); |
-1 -3 -5