Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does this recursive function with no parameters work?

This function calculates the length of a singly linked list recursively.

tail is an instance variable that points to the next object in the list.

    public int length() {
        if (tail == null) {
            return 1;
        }

        return 1 + tail.length();
    }

However it uses no parameters as shown. I’m struggling to understand the logic behind this code, could I get some help with understanding what’s actually going on here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My first point of confusion is when the function reaches the last object in the list, that objects tail will be null, so why does the function not just end up returning 1?
And secondly, what does 1 + tail.length() actually do.

The most I understand is that 1 and tail.length() can be added due to the length function having a return type of int.

>Solution :

Let’s assume you have a list like [a, b, c, d] and you’re calling length() on it. this will be the element a and tail will be the next element b. So the flow of the code should be something like this:

this.length() // Element 'a'
Is tail == null? // No, tail is 'b'
return 1 + <result of length() of 'b'>
|
|   this.length() // Element 'b'
|   Is tail == null? // No, tail is 'c'
|   return 1 + <result of length() of 'c'>
|   |
|   |   this.length() // Element 'c'
|   |   Is tail == null? // No, tail is 'd'
|   |   return 1 + <result of length() of 'd'>
|   |   |
|   |   |   this.length() // Element 'd'
|   |   |   Is tail == null? // Yes, there's no element after 'd' so return 1
|   |   |   return 1 // return 1 from length() of 'd'
|   |   |
|   |   return 1 + 1 // return 2 from length() of 'c'
|   |
|   return 1 + 2 // return 3 from length() of 'b'
|
return 1 + 3 // return 4 from length() of 'a'

So in the end, length() will give you the correct result of 4

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading