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

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo πŸ“Šβœ¨

Top comments (0)