Nihal Sharma Nihal Sharma - 1 month ago 8
Java Question

Check if a linkedlist is palindrome (Recursively)

I am trying with the below code, but the result is always

true
;

public boolean isPallindrome(Link link, Link right) {
if (right == null)
return true;

if (!isPallindrome(link, right.getNext())) {
return false;
}
boolean isP1 = right.getData() == link.getData();
link = link.getNext();
return isP1;
}


Calling: -

System.out.println(link1.isPallindrome(link1.getFirst(), link1.getFirst()));


I think the culprit is the return from where
right
is checked against
null
. It is one which might be returning
true
always. Can some one suggest how to fix this.

Answer

This is what your algorithm will look like

boolean flag=true;
public boolean checkPalindrome(List nodeList,boolean flag)
{
    if(flag==false)
        return false;
    if(nodeList.right==null)
        return flag;
    else{
        Node n;//reference for travelling till last node
        //traverse till last node

        //check first and last node

        if(same){
            //delete both nodes;
        }
        else{
            flag=false;
        }
        return checkPalindrome(nodeList,flag)

    }
}

this is just a pointer you need to take it forward.

If at all you need the original list back again, then you might want to copy list contents in other object and use that object in this method

Hope this helps!

Good Luck!