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! πŸš€

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay