Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
1. Reverse later half part
2. two pointer go through list, one from front and end
public boolean isPalindrome(ListNode head) {
if(head ==null || head.next == null) return true;
//get middle node,
ListNode l1 = head;
ListNode l2 = head;
while(l2.next!=null){
l1 = l1.next;
if(l2.next.next == null){
l2 = l2.next;
break;
}
l2 = l2.next.next;
}
//reverse linked list
l2 = l1.next;
while(l2!=null) {
ListNode l3 = l2.next;
l2.next = l1;
l1 = l2;
l2 = l3;
}//l1 is the last one
//two pointer from front and end
l2 = head;
while(l2 != l1 && l2.next!=l1){
if(l1.val != l2.val)
return false;
l1 = l1.next;
l2 = l2.next;
}
if(l2.next == l1) return l2.val == l1.val;
return true;
}