Challenge: Find the Length of a Linked List

Can you find the length of a linked list given as input to your function? A solution is placed in the "solution" section for your help, but we would suggest that you try to solve it on your own first.

Problem Statement #

In this problem, you have to implement the method int length(), which will count the number of nodes in a linked list. An illustration is also provided for your understanding.

Method Prototype #

int length()

Output #

The length of the given linked list.

Sample Input #

linkedlist = 0->1->2-3->4

Sample Output #

length = 5 

The figure below illustrates how length is calculated in a non-empty list:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.