DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - Singly Linked Lists: Playing Detective with `find(data)` πŸ•΅οΈβ€β™‚οΈ

Hello Dev.to enthusiasts! 🌟

We've been on quite the journey with singly linked lists, haven't we? After adding, deleting, and printing nodes, let's put on our detective hats and learn how to search with the find(data) method.

A Tiny Flashback: Singly Linked List πŸ“œ

For those who've just tuned in:

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

class SinglyLinkedList {
    Node head;
    SinglyLinkedList() {
        this.head = null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Each node is a tiny vault of data, safely guarded and pointing to its successor.

Launching the Search Party with find(data) πŸ”

Think of the find(data) method as your personal detective.

public Node find(int data) {
    // We kick off our investigation at the head of the list
    Node current = head;

    // As long as there are nodes loop
    while (current != null) {
        // If we get a match, case closed!
        if (current.data == data) {
            return current;
        }
        // If not, we continue our inquiry
        current = current.next;
    }

    // If not found, it's a null report
    return null;
}
Enter fullscreen mode Exit fullscreen mode

Why Bother Searching? πŸ€”

Well, what's a list without the ability to find specifics in it? Whether you're validating data, making updates, or simply checking for the existence of a value, find(data) ensures your list is more than just a passive container.

Conclusion 🎀

Armed with the find(data) method, we are ready to transform singly linked list into an interactive database of possibilities.

In the next article we will look at get(index) method

Cheers and happy coding! πŸš€

Top comments (0)