DEV Community

HunorVadaszPerhat
HunorVadaszPerhat

Posted on

Java - Understanding the Singly Linked List: Counting Nodes with size()

Greetings, Dev.to tribe! ๐ŸŒ

We've previously dipped our toes into the world of singly linked lists. Today, we're diving a bit deeper to tackle a common, yet crucial question: "How big is this thing?" Enter the stage: the size() method.

Quick Refresher: Singly Linked List ๐Ÿ“œ
In case you missed our previous chatter, here's what a basic singly linked list setup looks like:

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 carries data and a reference to the next node. If there's no next node, it points to the vast emptiness of null.

Unveiling the size() Method ๐Ÿงฎ
Now, to the star of today's show. How do we figure out the length of our linked list?

public int size() {
    int count = 0;
    Node currentNode = head;

    while (currentNode != null) {
        count++;
        currentNode = currentNode.next;
    }

    return count;
}
Enter fullscreen mode Exit fullscreen mode

We start at the head of the list and traverse through, incrementing our count with each node we visit. When we hit null, it's game over and we return our count.

Why Does Size Matter? ๐Ÿค“
Whether you're allocating resources, indexing, or just generally curious it helps ensure efficiency and gives you a solid grasp of the data you're working with.

Signing Off ๐ŸŽค
And that's a wrap on the size() method! Until next time, keep those nodes connected!

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

Cheers to another day of coding mastery! ๐ŸŽ‰๐Ÿš€

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil โ€” patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

AWS Security LIVE! Stream

Stream AWS Security LIVE!

The best security feels invisible. Learn how solutions from AWS and AWS Partners make it a reality on Security LIVE!

Learn More

๐Ÿ‘‹ Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple โ€œthank youโ€ can uplift someoneโ€™s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay