Java - Understanding the Singly Linked List: Counting Nodes with size()
HunorVadaszPerhat
Posted on August 26, 2023
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;
}
}
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;
}
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! 🎉🚀
Posted on August 26, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.