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?
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null) return true;
ListNode slow = head;
ListNode fast = head;
int count = 1;
while(fast.next!=null&&fast.next.next!=null){
slow = slow.next;
fast = fast.next.next;
count++;
}
ListNode pre = slow;
ListNode cur = slow.next;
while(cur!=null){
ListNode nextNode = cur.next;
cur.next = pre;
pre = cur;
cur = nextNode;
}
while(count>0){
if(pre.val!=head.val) return false;
head=head.next;
pre=pre.next;
count--;
}
return true;
}
}
黄色部分是总是出错的地方!!!