DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - 🧐 Checking Out if Empty with `isEmpty()`: Doubly Linked List πŸ“–

Hey Dev.to folks! πŸ‘‹

When dealing with a doubly linked list, there's an easy way to check if it's a full house or a lonely room.πŸ₯³ Here comes the isEmpty() method.

πŸ“˜ Quick Doubly Linked List Refresher:

Before we dive in, let's recall our framework:

class Node {
    int data;
    Node next;
    Node prev;

    // Constructor: Crafting our node from scratch
    Node(int data) {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}

class DoublyLinkedList {
    Node head;
    Node tail;

    // Constructor: Setting the stage 
    DoublyLinkedList() {
        this.head = null;
        this.tail = null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Remember, each node in our doubly linked list has knowledge of both its previous and next neighbor. 🀝

πŸ•΅οΈβ€β™‚οΈ Diving into isEmpty():

Here's the quick insight on how...:

public boolean isEmpty() {
    return head == null;  // If no head, no party!
}
Enter fullscreen mode Exit fullscreen mode

Super straightforward, right? If there's no head node, then the list is empty!

🎈 Why isEmpty() is Your New BFF(I mean FOREVER!):

Ever tried inserting or deleting from a list? Knowing whether it’s populated can save you from situations you would not admit later on in life. Trying to work with non-existent nodes___? πŸ€·β€β™‚οΈ

πŸŽ‰ Wrapping Things Up:

The isEmpty() method: your first line of defense. It ensures you're not talking to yourself (though a rubber duck can help to catch thoughts πŸ¦† ), and trust me, that’s a great feature to have.

Cheers and happy coding! πŸš€

Top comments (0)