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

Top comments (0)