Last Updated: 06 October, 2024 5 Mins
In this Linked List tutorial, we will see and learn how to find the length of a Linked List. The length of a linked list is the total number of nodes present in a linked list.
Examples:
Linked List: 80 -> 20 -> 70 -> 50 -> 30
Length of Listed List: 5Linked List: 80 -> 20 -> 70 -> 50 -> 30 -> 10 -> 90 -> 40
Length of Listed List: 8There are basically two approaches to find a length of a linked list:
Following are the steps we need to follow to find the length of the Linked List using Iterative approach:
In the below given example we will see the implementation of Iterative approach in Java.
Output
Length of the linked list is: 5
After adding two new nodes, length of the linked list is: 7
Time complexity: O(N), Where N is the length of the linked list.
Auxiliary Space: O(1), As constant extra space is used.
To implement the recursive approach, we defined a function called countTotalNodes(node). This function takes a node as an argument and calls itself with the next node until we reach the end of the linked list. Each of the recursive calls returns 1 + the count of remaining nodes.
In the below given example we will see how to find the length of a linked list using Recursive approach in Java.
Output
Length of the linked list is: 5
After adding two new nodes, length of the linked list is: 7
Time complexity: O(N), Where N is the length of the linked list.
Auxiliary Space: O(N), Extra space is used in the recursion call stack.
That's all, guys. I hope this article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com