DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - 🚫 `removeAt(index)`: cleaning with one Index at a Time πŸ—‘οΈ

Hello Dev.to enthusiasts! 🌟

In the realm of data structures, sometimes we need to let go. Maybe it's that piece of redundant data or just an old value taking up precious space. Introducing removeAt(index)!!!

🏒 Brief Elevator Pitch: The Singly Linked List

Just in case someone's late to the party:

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

Each node in our list holds some data and a pointer to the next node, or null if it's the last one in line.

🧹 Breaking Down removeAt(index)

Here's our clean-up strategy:

public void removeAt(int index) {
    // If the building's empty, LEAVE!
    if (head == null) return;

    // IF first floor you might be walking!
    if (index == 0) {
        head = head.next;
        return;
    }

    Node current = head;
    int count = 0;

    // Go floor by floor until your floor is found.
    while (current != null && count < index - 1) {
        current = current.next;
        count++;
    }

    // If we're at the right floor and there's an apartment to find out
    if (current != null && current.next != null) {
        current.next = current.next.next;
    }
}
Enter fullscreen mode Exit fullscreen mode

🎈 Why removeAt(index)?

The removeAt(index) method helps us strike the right balance in our data structures.

πŸŒ„ In Conclusion

With removeAt(index) in your coding arsenal, you’re equipped to manage your data structures. ✨

In the next article we will look at reverse() 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