Java - Finding Your Node's Place with `get(index)`! 💁‍♂️

hunorvadaszperhat

HunorVadaszPerhat

Posted on August 27, 2023

Java - Finding Your Node's Place with `get(index)`! 💁‍♂️

Hey Dev.to enthusiasts!

Diving back into the maze of singly linked lists, have you ever felt like wanting a GPS to zoom straight to a node? Well, get(index) might just be the navigator you need.

Quick Lay of the Land: Singly Linked List

For those just catching up:

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

Deciphering get(index)

Here's a breakdown:

public Node get(int index) {
    // If list is empty exit!
    if (head == null) return null;

    // We start at the starting line.
    Node current = head;
    int count = 0;

    // Race through the checkpoints.
    while (current != null) {
        if (count == index) {
            return current; // If found early return!
        }
        count++;
        current = current.next;
    }

    // If our index is out of bounds, return null.
    return null;
}
Enter fullscreen mode Exit fullscreen mode

Why Rely on get(index)? 🧭

Navigating data structures requires precision. With singly linked lists, get(index) ensures you can find your data based on position.

To Conclude

With get(index) in your toolkit, you're equipped to move through your linked list with direction and purpose.

In the next article we will look at clear() method

Cheers and happy coding! 🚀

💖 💪 🙅 🚩
hunorvadaszperhat
HunorVadaszPerhat

Posted on August 27, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related