How to use While Loop In Javascript

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)

JavaScript Program to Print Even Numbers in a Linked List

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.

Table of Content

  • Using While Loop
  • Using Recursion

Similar Reads

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

Using Recursion

...