0
public static boolean checkPallindrone(Node<Integer> head,Node<Integer> last){

    //# check if the given linked list is a palindrome

    boolean check = true;
    if(head==null || head.next==null){
        return true;
    }

    if(head.data != last.data){
        return false;
    }

    Node<Integer>temp = head;
    while(temp.next.next !=null){
        temp= temp.next;
    }
    last = temp;
    last.next=null;
    check = checkPallindrone(head.next, last);

    if(check == false){
        return false;
    }

    else return true;
}

This is a code snippet to find palindrome. In this code the object head and last are send to the function. In java all the objects are references as I had read somewhere. So here head and last are reference which would point or refer to a linked list in the heap of applications memory structure. So why when I print the linked list in the main function, do I not get an empty linked list, Since last would make all the elements NULL one by one in the process of checking if its a palindrome?

janos
  • 120,954
  • 29
  • 226
  • 236
Meraki
  • 3
  • 3
  • `do I not get an empty linked list, Since 'last' would make all the elements NULL` - no, you are calling `last.next=null;` to at most half the elements of the list, so at least the first half of the list will remain. – Eran Jul 10 '16 at 11:04
  • each time recursively we are accessing temp=last-1, then making temp.next as null. – Meraki Jul 10 '16 at 11:09
  • But once `head` reaches the middle of the list, `head.next` will be null and you will return true. – Eran Jul 10 '16 at 11:17
  • Yes, but my question is why is the same not being reflected in the main ? Why when I try to print the linked list all elements are present and are not null? – Meraki Jul 10 '16 at 11:23

0 Answers0