DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - 🎯 `insertAt(index, data)` in Your Singly Linked List 📍

Hello Dev.to enthusiasts! 🌟

In our coding lives, there are times when we desire precision. When inserting data 🩺 in a data structure, we want control. Enter the realm of insertAt(index, data) for the singly linked list.

🏰 Quick Castle Tour: The Singly Linked List

A tiny refresher for our wandering minds (like mine!):

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

🧐 Decoding insertAt(index, data)

Here's our blueprint:

public void insertAt(int index, int data) {
    Node newNode = new Node(data);

    // If the list is empty or you're adding right at the front
    if (head == null || index == 0) {
        newNode.next = head;
        head = newNode;
        return;
    }

    Node current = head;
    int count = 0;

    // Loop through the list until you find the perfect node or reach the end
    while (current != null && count < index - 1) {
        current = current.next;
        count++;
    }

    // Found the spot? Great!
    if (current != null) {
        newNode.next = current.next;
        current.next = newNode;
    }
}
Enter fullscreen mode Exit fullscreen mode

🤔 Why Embrace insertAt(index, data)?

Flexibility 🤸‍♂️. Rather than always adding rooms to the end or the beginning, this method gives us the freedom to choose our exact position.

💡 Wrapping Up

The insertAt(index, data) method is like having a precision tool 🔍 in your coding toolkit.

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

Cheers and happy coding! 🚀

Java-ready auth and billing that just works

Java-ready auth and billing that just works

Stop building auth from scratch. Kinde handles authentication, user management, and billing so you can focus on what matters - shipping great products your users will love.

Get a free account

Top comments (0)

Heroku

Tired of jumping between terminals, dashboards, and code?

Check out this demo showcasing how tools like Cursor can connect to Heroku through the MCP, letting you trigger actions like deployments, scaling, or provisioning—all without leaving your editor.

Learn More

👋 Kindness is contagious

Explore this practical breakdown on DEV’s open platform, where developers from every background come together to push boundaries. No matter your experience, your viewpoint enriches the conversation.

Dropping a simple “thank you” or question in the comments goes a long way in supporting authors—your feedback helps ideas evolve.

At DEV, shared discovery drives progress and builds lasting bonds. If this post resonated, a quick nod of appreciation can make all the difference.

Okay