DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on • Updated on

Java - ๐Ÿ“ Measuring Up `size()`- Doubly Linked List ๐Ÿ“–

Hey Dev.to folks! ๐Ÿ‘‹

Want to know how many nodes are in your doubly linked list? Look no further: here comes the size() method.

๐Ÿ“˜ Quick Doubly Linked List Recap:

Hereโ€™s our foundational setup:

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

    // Constructor to initialize the node
    Node(int data) {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}

class DoublyLinkedList {
    Node head;
    Node tail;

    // Constructor to initialize the doubly linked list
    DoublyLinkedList() {
        this.head = null;
        this.tail = null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Remember, in a doubly linked list, each node knows about its next and previous node. ๐Ÿ”„

๐Ÿงฎ Breaking Down size():

Let's get counting:

public int size() {
    int count = 0;          // Initialize the counter to zero
    Node current = head;    // Start at the beginning of the list

    while (current != null) {
        count++;            // Increase the counter for each node
        current = current.next; // Move to the next node in the list
    }

    return count;           // Return the total number of nodes
}
Enter fullscreen mode Exit fullscreen mode

The gist is simple: start at the head, traverse the list, and count each node until you reach the end.

๐Ÿ” Why size() Matters:

Knowing the size of your list can be essential, especially when you're adding, removing, or accessing elements.

๐ŸŽ‰ In Conclusion:

The size() method is a basic but essential tool for managing a doubly linked list. ๐Ÿš€

In the next article we will look at isEmpty() method

Cheers and happy coding! ๐Ÿš€

Top comments (0)