Find length of Linked List in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm programs.

In this post, we will see how to find length of Linked List in java.
You can obviously use size() method of java Linked List class but here we are going to see how to find length of Linked List when you implement Linked List yourself.
There are two ways to find length of linked list:

  • Iterative
  • Recursion

Iterative:

You can iterate over next nodes until node is null and use counter to count number of iteration and you will get length of linked list in the end.

Recursion:

You can use recursion also to find length of linked list. Base case: If node is null, return 0. This will be base case of our iteration.

Java program to find length of LinkedList:

Create a java file named SinglyLinkedList.java.

Let’s create Main class named LinkedListMain.java to create LinkedList.
When you run above program, you will get below output:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *