DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on โ€ข Edited 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! ๐Ÿš€

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

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