JavaScript Program to Print Positive Numbers in a Linked List

This JavaScript program aims to print positive 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 positive numbers encountered.

Table of Content

  • Iterative Approach
  • Recursive Approach

Iterative Approach

In this method, we will traverse the linked list using a loop, checking each element if it is positive, and printing it if so.

Example: The below example prints positive 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 printPositiveNumbersIterative(head) {
    let current = head;
    while (current !== null) {
        if (current.value > 0) {
            console.log(current.value);
        }
        current = current.next;
    }
}
const linkedList =
    createLinkedList([-1, 2, -3, 5, 4, -5]);
printPositiveNumbersIterative(linkedList.head);


Output

2
5
4

Recursive Approach

Implement a recursive function to traverse the linked list, checking each element recursively and printing the positive numbers encountered.

Example: The below example is to print positive 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 printPositiveNumbersRecursive(node) {
    if (node === null) {
        return;
    }
    if (node.value > 0) {
        console.log(node.value);
    }
    printPositiveNumbersRecursive(node.next);
}
const linkedList =
    createLinkedList([-1, 2, 5, -3, 4, -5]);
printPositiveNumbersRecursive(linkedList.head);


Output

2
5
4