Open In App

JavaScript Program to Print Negative Numbers in a Linked List

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

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.

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.

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);


Output

-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.

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);


Output

-1
-3
-5


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads