Java,function does not recognize the return statements

RohitDubey22 :

While writing a code for checking if a linked list is pallindrome or not,I created a reverseLL function which returns a reversed linked list and a isPallindrome function to check.The problem is that the return statement inside the loop is not being detected and only the last statement which is return true; is being executed every time: I am checking if the LL is pallindrome by dividing it into 2 parts and reversing the second half,then comparing both the halves

public static Node<Integer> reverseLL(Node<Integer> head){
    Node<Integer> prev = null;
    Node<Integer> current = head;
    Node<Integer> next = null;
    while(current != null) {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
    head = prev;
    return head;
}
public static boolean isPallindrome(Node<Integer> head) {
    if(head == null || head.next == null) {
        return true;
    }

    Node<Integer> fast = head;
    Node<Integer> slow = head;

    while(fast.next != null && fast.next.next != null) {
        fast  = fast.next.next;
        slow = slow.next;
    }

    Node<Integer> secondHead = slow.next;
    slow.next = null;
    secondHead = reverseLL(secondHead);

    Node<Integer> p = secondHead;
    Node<Integer> q = head;
    while(p != null) {
        if(p.data != q.data) {
            return false;
        }
        p = p.next;
        q = q.next;
    }
    return true;
}
Torben :

I'm not going to run your code because it is not complete. However, it looks like you find the last element of the list and reverse it from there without taking into consideration that it also reverses the list yuo are already referring to with head. So when you start the comparison loop you have a pointer to the first element in the reversed list and a pointer to the last element in the reversed list. You are definitely not splitting the list to two parts.

Your code is also overly complicated. The correct algorithm is:

find head and tail of list
while (head != tail) {
    if (head.value != tail.value)
        return false;
    head = head.next;
    tail = tail.prev;
}

You don't need two loop variables to find the tail of a linked list. The correct algorithm is:

tail = head
while (tail.next != null) {
    tail = tail.next;
}

Also, you can't generally compare Integers with equality operator. You have to either unbox them to primitive ints or use equals. Try running:

System.err.println(new Integer(1) == new Integer(1));
System.err.println(new Integer(1).equals(new Integer(1)));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=416894&siteId=1