Open In App

JavaScript Program to Print all Odd Elements in a Sorted Order of a Linked List

This JavaScript program aims to print all odd elements in a sorted order of 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 odd elements in a sorted order of a linked list

Iterative Approach

The elements of the linked list are traversed using a loop and each one of them is checked for the odd value. It prints the odd values on the console.

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

Output
1
3
5

Recursive Approach

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

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

Output:

1
3
5

Article Tags :