Open In App

JavaScript Program to Print Even Numbers in a Linked List

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

A linked list is a data structure that stores the values at different memory locations concerning the next memory block of stored value.

You can get all the even numbers stored in a linked list using the below methods.

Using While Loop

To print even numbers in a linked list using the while loop method, we go through each element one by one until we reach the end. At each step, we check if the number is even or not, and if it is even, we print it.

Example: The below code implements the while loop to print even numbers in a linked list.

Javascript




class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 
class LinkedList {
    constructor() {
        this.head = null;
    }
 
    addNode(data) {
        let new_Node = new Node(data);
        new_Node.next = this.head;
        this.head = new_Node;
    }
 
    evenNumbers() {
        let current = this.head;
        while (current !== null) {
            if (current.data % 2 === 0) {
                console.log(current.data);
            }
            current = current.next;
        }
    }
}
 
let linkedList = new LinkedList();
linkedList.addNode(7);
linkedList.addNode(10);
linkedList.addNode(8);
linkedList.addNode(3);
linkedList.addNode(2);
 
console.log("Even numbers in the linked list:");
linkedList.evenNumbers();


Output

Even numbers in the linked list:
2
8
10

Time Complexity: O(n)

Space Complexity: O(1)

Using Recursion

This method recursively checks each node in the linked list to determine if current node’s data stores an even number, if it is even then it simply print it.

Example: The below code implements recursion to check for the even numers in the linked list.

Javascript




class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 
class LinkedList {
    constructor() {
        this.head = null;
    }
 
    addNode(data) {
        let new_Node = new Node(data);
        new_Node.next = this.head;
        this.head = new_Node;
    }
 
    evenNumbers(current) {
        if (current === null) {
            return;
        }
 
        if (current.data % 2 === 0) {
            console.log(current.data);
        }
 
        this.evenNumbers(current.next);
    }
}
 
let linkedList = new LinkedList();
linkedList.addNode(5);
linkedList.addNode(4);
linkedList.addNode(3);
linkedList.addNode(2);
linkedList.addNode(1);
 
console.log("Even numbers in the linked list are:");
linkedList.evenNumbers(linkedList.head);


Output

Even numbers in the linked list are:
2
4

Time Complexity: O(n)

Space Complexity: O(n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads