Krishna krish
Krishna krish

Reputation: 67

based on recursion using java

public void length() {
    System.out.println(length(head, 0));
}
public int length(Node he, int count) {
    if(he!=null) {
        // System.out.println(he.data +"   "+count++);
        // count++;
        // return length(he.next, count);
        return length(he.next, count++);
    }
    return count;
}

In the code above, I have to find the length of linked list. If I run the same code, I am getting the length 0.But, when i use commented code and I am getting the correct length. Why is that happening?

Upvotes: 1

Views: 86

Answers (2)

burakozgul
burakozgul

Reputation: 797

Use

return length(he.next, ++count);

or

System.out.println(he.data +"   "+count);
count++;
return length(he.next, count);

I will try to simulate your and my code.

Your code :

//count = 0

length(he.next, count++) // length(he.next, 0) 

//after recursion call count increments , count = 1

My code :

//count = 0

// before recursion call, ++count increments count 

// count = 1 

length(he.next, ++count) // length(he.next, 1) 

Guys im new here if im wrong, please edit me :)

Upvotes: 0

Eran
Eran

Reputation: 393841

length(he.next, count++) passes the original value of count to the method call, since you are using the post increment operator. Therefore you are always passing 0.

length(he.next, ++count) would work, since here the incremented value of count will be passed.

In your commented code you are not passing the value of count++ to the method call, you are passing count after it was already incremented, which also works.

Upvotes: 5

Related Questions