mardi 4 février 2020

Java,function does not recognize the return statements

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;
}

Aucun commentaire:

Enregistrer un commentaire