How do I recursively calculate the number of elements in a list?

602 views Asked by At
Public class ListItem{

   final int number;
    ListItem next;


ListItem(int number, ListItem next) {
        this.number = number;
        this.next   = next;
    }

public int length() {
        if(this.next != null){
            this.next = this.next.next;
            return 1 + this.length();
        }
        else return 0;
    }

When I've been trying to calculate the length, I have been getting the length to be 1 lower than the expected length. For example, if the length is 10, I would get 9. How can I fix this issue?

Thanks.

1

There are 1 answers

0
Austio On BEST ANSWER

Your last value is returning 0 because this.next is null. So you are adding everything except the last element, hence you are returning lenght -1. I come from a Ruby background and haven't programmed Java in 10 years, but it would be more like this below, syntax may be off.

Also, generally for recursive stuff your base case for returning is going to be the first line of the function.

Public class ListItem{
  final int number;
  ListItem next;


ListItem(int number, ListItem next) {
    this.number = number;
    this.next   = next;
}

 public int length() {
    if(this.next == null){
        return 1; 
    }
    else {
        return 1 + this.next.length;
    }
}