class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null){
return true;
}
ListNode slow = head;
ListNode fast = slow.next;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode half = slow.next;
if(fast.next != null){
half = half.next;
}
half = reverse(half);
while(half != null){
if(head.val != half.val){
return false;
}
half= half.next;
head = head.next;
}
return true;
}
public ListNode reverse(ListNode head){
ListNode cur = head;
ListNode pre = null;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
|