注意,如果用的方法是翻转整个链表,那么链表都被改变了。就无法做了。
此外注意fast.next.next!= null;不然也会报错。要保证后面的比前面的少。
答案:
public static boolean isPalindrome(ListNode head){ if(null == head || null == head.next) return true;
ListNode slow = head;
ListNode fast = head;
while(fast != null && null != fast.next && fast.next.next != null ){
slow = slow.next;
fast = fast.next.next;
}
ListNode newHead = reverseList(slow.next); while( newHead != null){
if(head.val != newHead.val){
return false;
}
head = head.next;
newHead = newHead.next;
}
return true;
}
public static ListNode reverseList(ListNode head){
ListNode newHead = null;
ListNode tmp = null;
while(head != null){
tmp = head;
head = head.next;
tmp.next = newHead;
newHead = tmp;
}
return newHead; }