 
思路:先用快慢指针找到中间点,然后把后半部分翻转,然后同时遍历前半部分和后半部分,都一样就是回文链表。
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
if(head.next.next == null) return head.val == head.next.val;
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode newRightHead = resverse(slow.next);
ListNode newLeftHead = head;
while(newRightHead != null ){
if(newLeftHead.val != newRightHead.val){
return false;
}
newRightHead = newRightHead.next;
newLeftHead = newLeftHead.next;
}
return true;
}
private ListNode resverse(ListNode head){
if(head == null || head.next == null) return head;
ListNode newHead = resverse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
反转链表部分的解析
|