Search code examples
javalinked-listpalindrome

Reverse and Compare Palindrome Solution (Cracking the Coding Interview)


so I am going through the Cracking the Coding Interview book. I am working on this problem:

"Implement a function to check if a linked list is a palindrome"

I noticed that the first solution (page 217) provides just a node as the argument to the functions, rather than the whole list. I was just wondering, how is it that the functions know the next node in the list, without the list provided?

I have provided the code below, just in case.

boolean isPalindrome(LinkedListNode head){
  LinkedListNode reversed = reverseAndClone(head);
  return isEqual(head, reversed);
}
LinkedListNode reverseAndClone(LinkedListNode node){
  LinkedListNode head = null;
  while(node != null){
   LinkedListNode n = new LinkedListNode(node.data);
   n.next = head;
   head = n;
   node = node.next;
  }
  return head;
}

boolean isEqual(LinkedListNode one, LinkedListNode two) {
  while(one != null && two != null){
    if (one.data != two.data){
      return false;
    }
  one = one.next;
  two = two.next;
  }
 return one == null && two == null;
}

Solution

  • In a linked list, each node holds its own data and a reference to the next node in the list (and possibly also to the previous item, in a doubly-linked list, which does not seem to be the case here). So you don't really need the list wrapper to get all its data, just a reference to the first node (the head), as shown in the snippet you included.