How to use Recursive Approach In Javascript

This recursive method checks each node in the linked list to determine if the current node’s data represents an odd number, and if so, it is printed.

Example: This example shows the use of the above-explained approach.

Javascript




// JavaScript program to print odd numbers
// in a linked list using recursive approach
 
// Node class represents each element in
// the linked list
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}
 
// LinkedList class manages the
// linked list operations
class LinkedList {
  constructor() {
    this.head = null;
  }
 
  // Method to add a new node at the
   //beginning of the linked list
  addNode(data) {
    let newNode = new Node(data);
    newNode.next = this.head;
    this.head = newNode;
  }
 
  // Recursive method to print
  // odd numbers in the linked list
  oddNumbers(current) {
    // Base case: if current node is null, return
    if (current === null) {
      return;
    }
 
    // Check if the data of the current node
    // is odd, and print if true
    if (current.data % 2 !== 0) {
      console.log(current.data);
    }
 
    // Recursive call for the next node in the linked list
    this.oddNumbers(current.next);
  }
}
 
// Example
let linkedList = new LinkedList();
linkedList.addNode(1);
linkedList.addNode(4);
linkedList.addNode(7);
linkedList.addNode(9);
linkedList.addNode(2);
 
// Displaying odd numbers in the linked list
// using the recursive approach
console.log(
    "Odd numbers in the linked list using recursive approach:");
linkedList.oddNumbers(linkedList.head);


Output

Odd numbers in the linked list using recursive approach:
9
7
1

Time Complexity: O(n)

Space Complexity: O(n)

JavaScript Program to Print Odd Numbers in a Linked List

This article will show you different ways to find and print all the odd numbers in a linked list using JavaScript.

Example:

Input: 2->1->9->3
Output: 1, 9, 3
Input: 5->5->1->0->19->8
Output: 5, 5, 1, 19

Table of Content

  • Using Recursive Approach
  • Using While Loop
  • Using For Loop

Similar Reads

Using Recursive Approach

This recursive method checks each node in the linked list to determine if the current node’s data represents an odd number, and if so, it is printed....

Using While Loop

...

Using For Loop

To print odd numbers in a linked list with the while loop method, we go through each node step by step until we reach the end of the list. At each node, we check whether the node’s data is odd, and if so, we display it....

Contact Us