Iterative Approach to Find Smallest Number in a Linked List

This method iterates through the list, initializing the smallest variable with the head node’s data and updating it. We find a smaller value at the node’s data. This approach traverses the list once. So time taken by this method is linear.

Example: Print the smallest number in the linked list using iteative method (while loop).

Javascript




class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
  
class LinkedList {
    constructor() {
        this.head = null;
    }
  
    addNode(data) {
  
        const newNode = new Node(data);
        if (!this.head) {
            this.head = newNode;
        } else {
            let current = this.head;
            while (current.next) {
                current = current.next;
            }
            current.next = newNode;
        }
    }
  
    findSmallest() {
        if (!this.head) {
            return null;
        }
  
        let current = this.head;
        let smallest = current.data;
  
        while (current) {
            if (current.data < smallest) {
                smallest = current.data;
            }
            current = current.next;
        }
  
        return smallest;
    }
}
  
// Example
const linkedList = new LinkedList();
linkedList.addNode(3);
linkedList.addNode(1);
linkedList.addNode(4);
linkedList.addNode(2);
  
let smallest = linkedList.findSmallest();
console.log("Smallest number in the linked list:", smallest);


Output

Smallest number in the linked list: 1

Time Complexity: O(n)

Space Complexity: O(1)

JavaScript Program to Find Smallest Number in a Linked List

Given a linked list, the task is to find the smallest number in a linked list in JavaScript. A “linked list” is a data structure to store data where each piece of information is connected to the next one, forming a chain. Each piece has its data and knows where to find the next piece. It’s a basic but useful method to organize and manage data.

Here, we have given a linked list, and the task is to find the smallest number within the linked list.

Examples:

Input: 3 -> 4 -> 1 -> 7 -> 5
Output: 1

Input: 2 -> 7 -> 5 -> 5 -> 8 -> 4
Output: 2

Table of Content

  • Iterative Approach
  • Recursive Approach

Similar Reads

Iterative Approach to Find Smallest Number in a Linked List

This method iterates through the list, initializing the smallest variable with the head node’s data and updating it. We find a smaller value at the node’s data. This approach traverses the list once. So time taken by this method is linear....

Recursive Approach to Find Smallest Number in a Linked List

...

Contact Us