Thursday, September 21, 2023

 Find the length of a Linked List in Java



In this post, we will see the ways we can determine the length of a Singly-Linked list in Java.

We can use iterative and recursive approaches.|


Find the length of a Linked List - iterative

Here, we are iterating through the linked list and counting the number of iterations which will give us the length of the list when we get to be end and exit the while loop.

public int findLength() {
if (head == null) {
return 0;
}

Node<T> current = head;
int count = 0;

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

return count;
}


Note: we added the findLength method to our custom implementation of the LinkedList.


Find the length of a Linked List - recursive

This is not difficult if you are familiar with how recursion works.

public int findLength(Node<T> current) {
if (current == null) {
return 0;
}

return 1 + findLength(current.next);
}


On each method call we add the 1 to the result and when we get to the point when the current becomes null (our base case), we return 0 and finish with recursive calls.
This approach is very similar to finding the factorial of a number.


That is all about how to find the length of a Linked List in Java.





No comments:

Post a Comment