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;
}
}
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;
}
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)