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! ๐ŸŽ‰๐Ÿš€

Top comments (0)