This code checks if a linked list is a palindrome.
When I compare the two values in my list that are greater than 127 it will return that the values are always not equal for example running [1, 128, 100, 100, 128, 1] the code will return 128 != 128 unless I cast them to int within the if statement.
I'm just curious as to why this is happening. Here's my code:
while(firstHalf != null && secondHalf != null)
{
//COMPARISON ONLY WORKS WHEN CASTED TO AN INT
if(((int)firstHalf.value) != ((int)secondHalf.value))
{
return false;
}
firstHalf = firstHalf.next;
secondHalf = secondHalf.next;
}
Entire method:
// Definition for singly-linked list:
// class ListNode<T> {
// ListNode(T x) {
// value = x;
// }
// T value;
// ListNode<T> next;
// }
//
boolean isListPalindrome(ListNode<Integer> l) {
if(l == null)
return true;
ListNode fastPnter = l;
ListNode slowPnter = l;
ListNode slowPnterPrev = l;
//find mid point
while(fastPnter != null && fastPnter.next !=null)
{
fastPnter = fastPnter.next.next;
slowPnterPrev = slowPnter;
slowPnter = slowPnter.next;
}
//odd case
if(fastPnter != null)
{
slowPnterPrev = slowPnter;
slowPnter = slowPnter.next;
}
//reverse second half
slowPnterPrev.next = null;
ListNode midNode = reverse(slowPnter);
//check halves
ListNode firstHalf = l;
ListNode secondHalf = midNode;
while(firstHalf != null && secondHalf != null)
{
//COMPARISON ONLY WORKS WHEN CASTED TO AN INT
if(((int)firstHalf.value) != ((int)secondHalf.value))
{
return false;
}
firstHalf = firstHalf.next;
secondHalf = secondHalf.next;
}
return true;
}