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

Top comments (0)