Spider
Spider

Reputation: 455

Trying to come up with solution using recursion

I know there are multiple ways to find out if a word is palindromic, like using the reverse function of StringBuilder or even the reverse function of Collections, but in an attempt to learn recursion, I wrote it this way. I even had it working iteratively.

I kind of added return true in my embedded else statement, but I'm really not sure what to do, because when I run this in debug mode, it returns false, then invokes checkPalindrome again, which I don't understand why, because it should return and terminate, no? I would really appreciate an explanation of what I'm doing wrong and how to get it working this way.

public static boolean checkPalindrome(Deque deq) {
    if(deq.pollFirst() != deq.pollLast()) {
        return false;
    } else {
        if(deq.size() == 1 || deq.size() == 0) {
            return true;
        } else {
            checkPalindrome(deq);
            return true // TODO ?? figure out What to put here ??
        }
    }
}

Upvotes: 1

Views: 67

Answers (1)

Rabbit Guy
Rabbit Guy

Reputation: 1892

It's that you are not returning anything when you call yourself. The inner else statement should read this:

else {
    return checkPalindrome(deq);
}

You have a followup question in the comments below that leads me to want to explain how recursive methods work, but in essence, they all follow the following pseudo-code:

public boolean someMethod(T[] someArrayOrList) {
    // return true  -OR-
    // return false -OR-
    // call yourself and return whatever that call returns
}

No matter what, when you call the method it will return SOMETHING... Either it will return something itself, or it will return whatever some other call of itself will return. In a way it is AND'ing all the responses, but in reality TRUE is only generated once.

Upvotes: 2

Related Questions