Given a singly linked list, I want to determine if it is a palindrome. For my method, I chose to reverse the first half of the linked list and then compare if the two halves of the linked list have equivalent elements. Previously, I placed the line fast = fast.next.next at the end of the first while loop(below the 4 other lines). However, when I did that, I received a Null Pointer Exception. Now, when I shift it to the first line in the while loop, I get no errors and my program is accepted. Can someone explain to me why this is so? Thank you! Below is my code:
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null){
return true;
}
ListNode fast = head;
ListNode slow = head;
ListNode prev = null;
while(fast != null && fast.next != null){
fast = fast.next.next;
ListNode temp = slow.next;
slow.next = prev;
prev = slow;
slow = temp;
}
if(fast != null){
slow = slow.next;
}
while(prev != null && prev.val == slow.val){
prev = prev.next;
slow = slow.next;
}
return slow == null;
}
}
fastwithin the body of the loop, the placement of the statementfast = fast.next.next;within the loop does not change the program's semantics. You should include the exception message, as well as the original code in your question.