JavaScript Program for Searching an Element in a Linked List

To search for an element in a linked list, we need to go through each node one by one and check if its value matches the target element. If we find the element, we return its position in the list. If not, we return a message saying the element is not found.

In this article, our task is to implement a JavaScript program that searches for a specific element in a linked list and returns its position if found, or a message if it is not present.

Example

Let's look at the below examples:

Linked list: 10 -> 20 -> 30 -> 40 -> null
Input: 40
Output: Element found at index 3
Input: 10
Output: Element found at index 0
Input: null
Output: Element not found

Approaches to Search an Element in a Linked List

Here, we will cover two approaches for searching an element in a linked list in JavaScript:

Pseudo Code

Below is the pseudo-code for searching an element in linked list:

ALGORITHM SearchInLinkedList(list, x)
  INPUT: list (Linked List), x (Target Element)
  OUTPUT: true if x is found, false otherwise

  1. Initialize current ? list.head
  2. WHILE current ? null DO
       a. IF current.data = x THEN
             RETURN true
       b. current ? current.next
  3. END WHILE
  4. RETURN false

Iterative Search in a Linked List

The iterative approach traverses the linked list from the head node to the end, checking each node's value against the target element. This method uses a simple loop to iterate through the nodes.

// Define the Node class for a singly linked list
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Define the LinkedList class
class LinkedList {
    constructor() {
        this.head = null;
        this.size = 0;
    }

    // Add an element to the linked list
    add(element) {
        const node = new Node(element);
        // If the linked list is empty, set the new node as the head
        if (this.head === null) {
            this.head = node;
        } else {
            // Traverse to the end of the linked list and add the new node
            let current = this.head;
            while (current.next !== null) {
                current = current.next;
            }
            current.next = node;
        }
        this.size++;
    }

    // Search for an element in the linked list
    search(element) {
        let current = this.head;
        let index = 0;
        // Traverse through the linked list until the element is found
        while (current !== null) {
            if (current.data === element) {
                return `Element found at index ${index}`;
            }
            current = current.next;
            index++;
        }
        return "Element not found";
    }
}

// Create a new linked list
const ll = new LinkedList();

// Add elements to the linked list
ll.add(10);
ll.add(20);
ll.add(30);
ll.add(40);
ll.add(50);

// Search for an element in the linked list
console.log(ll.search(30));
console.log(ll.search(100));
Element found at index 2
Element not found

Time Complexity: O(n), where n is the number of nodes in the list.

Space Complexity: O(1), as no extra space is used other than pointers for traversal.

Recursive Search in a Linked List

The recursive approach uses a helper function that calls itself to traverse the linked list. Each recursive call checks the current node and moves to the next node if the element is not found.

// Define the Node class for a singly linked list
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Define the LinkedList class
class LinkedList {
    constructor() {
        this.head = null;
        this.size = 0;
    }

    // Add an element to the linked list
    add(element) {
        const node = new Node(element);
        if (this.head === null) {
            this.head = node;
        } else {
            let current = this.head;
            while (current.next !== null) {
                current = current.next;
            }
            current.next = node;
        }
        this.size++;
    }

    // Recursively search for an element in the linked list
    searchRecursive(current, element, index = 0) {
        if (current === null) {
            return "Element not found";
        }
        if (current.data === element) {
            return `Element found at index ${index}`;
        }
        return this.searchRecursive(current.next, element, index + 1);
    }

    // Wrapper method for the recursive search
    search(element) {
        return this.searchRecursive(this.head, element);
    }
}

// Create a new linked list
const ll = new LinkedList();

// Add elements to the linked list
ll.add(10);
ll.add(20);
ll.add(30);
ll.add(40);
ll.add(50);

// Search for an element in the linked list
console.log(ll.search(30));
console.log(ll.search(100));
Element found at index 2
Element not found

Time Complexity: O(n), where n is the number of nodes in the list.

Space Complexity: O(n), as each recursive call adds a frame to the call stack, proportional to the number of nodes in the list.

Complexity Comparison

Here is a comparison of the time and space complexity for both iterative and recursive approaches:

Approach Time Complexity Space Complexity
Iterative Search O(n) O(1)
Recursive Search O(n) O(n) (due to call stack)

Key Points

  • Both approaches have linear time complexity O(n) in the worst case
  • The iterative approach is more memory-efficient with O(1) space complexity
  • The recursive approach uses O(n) space due to the function call stack
  • For large linked lists, the iterative approach is preferred to avoid stack overflow

Conclusion

Both iterative and recursive approaches effectively search elements in a linked list with O(n) time complexity. The iterative method is preferred for its constant space usage, while recursion offers cleaner code structure at the cost of additional memory overhead.

Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.
Updated on: 2026-03-15T23:19:01+05:30

654 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements