Recursion on linkedlist : how to compare?

Viewed 93

I'm currently working on recursion in linked list and I have a question where I have to compare two numbers in a linked list and I have to do it recursively.

It return true if all the elements on the list are in an ascending order.

Here what I've done in my List :

public boolean ascending() {
        if(this.first == null) return false;
        return this.first.ascending();
    }

Here what I've done in my Cells :

public boolean ascending() {
        if(this.next != null) {
            if(this.employee.getNumbers() < this.next.employee.getNumbers()) return true;
            this.next.ascending();
        } return false;
    }

The problem is that my code return true for 100 < 200 but false for 100 < 200 < 300 and true for 100 < 200 < 100.

Any suggestion? Thank you in advance!

2 Answers

You need to change your logic

You don't want to return true at all except if this.next is null because it means you ran out of numbers.

What you want to do is: for as long as I have numbers and the next one is bigger than the current one, keep looking. Otherwise return false. If I run out of numbers return true.

Like David Brossard explained you need something like:

public boolean ascending() 
{
        if(this.next == null)
           return true;
        else if(this.employee.getNumbers() < this.next.employee.getNumbers()) {
           return this.next.ascending();
        } 
        else return false;
 }
Related